I am using C++ to construct a trie tree with a bunch of words in dictionary. This is how I defined my TrieNode and built a tree:
struct TrieNode {
TrieNode *children[26];
bool isWord;
TrieNode(): isWord(false) {} /* to be deleted */
};
void buildTree(TrieNode *root, string word) {
TrieNode *cur = root;
for (char c : word) {
if (!cur->children[c-'a'])
cur->children[c-'a'] = new TrieNode();
cur = cur->children[c-'a'];
}
cur->isWord = true;
}
This works fine on some compilers, but on others this produces some strange results. For example, one time I found isWord was initialized to be 152, and the whole program crashed. I tried deleting the line marked above in the code, things worked out again. What is going on here?
Also, what is the difference between "new TrieNode()" and "new TrieNode"? Sometimes I found they produce different results too.