#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!