-1
#include <string>
using std::string;

class Trie
{
private:
    Trie* p[26];
    bool end;
    void clear(Trie* pt)
    {
        for (int i = 0; i < 26; ++i)
        {
            if (pt->p[i])
            {    
                clear(pt->p[i]);
                delete pt->p[i];
            }
        }
    }
public:
    Trie():p(), end(false)
    {}

    void insert(string word)
    {
        Trie* pt = this;
        for (int i = 0; i < word.size(); ++i)
        {
            int idx = word[i] - 'a';
            if (!pt->p[idx])
            {
                pt->p[idx] = new Trie();
            }
            pt = pt->p[idx];
        }
        pt->end = true;
    }

    ~Trie()
    {
        clear(this);
    }
};

I debug in VS and find that every time this line delete pt->p[i] is run, the deconstructor is called again and then call the clear() function recursively.

Moreover pt->p[i] would still point to the same block of memory except that it's inaccessible.

In the discuss section of this problem in leetcode, most solutions build a class TrieNode first so it wont cause problems if one deletes TrieNode but I just wonder if I can get my code work with only one class definition.

Great thanks in advance!

Tarse
  • 1
  • 1

1 Answers1

1

For a given i, you're clearing p[i] twice.

Once in: clear(pt->p[i]);

And a second time in delete pt->p[i]; which just calls clear(this) where this is the same pt->p[i] from the parent.

You should skip the clear(pt->pt[i]) call as that's handled by the destructor.

As for the pointer still existing, that's exactly what's supposed to happen. After delete pt->p[i], you can null pt->p[i].

PS: s/deconstructor/destructor/

Marc
  • 19,394
  • 6
  • 47
  • 51