c++ - 插入到 Trie 中,NULL 指针

标签 c++ pointers dictionary null trie

我有一个关于 Trie 数据结构的具体问题以及我的代码出了什么问题。当我递归调用 insert 时,函数参数 root 始终为 NULL。这是我的代码:

代码:

//subNodes is an array of TrieNode pointers that contains indices for all letters in the alphabet

bool insert(const string& word, TrieNode* root, int curI = 0)
//PRE:  word must be a valid word in a dictionary
//POST: True when a word is inserted into the Trie, false otherwise
{
    if(curI >= word.length())        //word has been scanned fully
    {
        root->isWord = true;
        return true;
    }
    else                             //word has more letters to be scanned
    {
        if(root->subNodes[word[curI] - 'A'] == NULL)    //if the current letter of the word is not in the trie
        {                                            //   insert the letter and advance the current letter of the word
            root->subNodes[word[curI] - 'A'] = new TrieNode(word[curI]);
            insert(word, root->subNodes[word[curI] - 'A'], curI++);
        }
        else                                         //if the currrent letter of the word is in the trie
        {                                            //   advance the current letter of the word
            insert(word, root->subNodes[word[curI] - 'A'], curI++);
        }
    }

}

我通过将 subNodes[word[curI] - 'A'] 替换为 subNodes[word[13]] (13是字母表中 N 的索引,我正在测试单词 not) 并且根不再是该调用的 NULL。因此索引出了问题。有谁知道出了什么问题?我考虑过使用 C++ 映射或 vector 。有人对使用数组有异议吗?

最佳答案

您是说 ++curl - 即将递增的值传递给递归调用吗?由于 curl++ 是后递增的,因此您将向每个递归传递相同的值。无论如何,只写 curl + 1 可能更容易,因为您不再需要 curl 值。

关于c++ - 插入到 Trie 中,NULL 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8720828/

相关文章:

c++ - 我的 C 风格字符串表现得很奇怪

pointers - Go中如何使用map作为数据载体?

c++ - 在C++中引用和指针的声明

c# - 如果字典没有被修改,Dictionary.Keys顺序保证是相同的吗?

c++ - VS2017 调试器 : has no address, 可能是由于编译器优化造成的

c++ - 获取错误 : 'mutex' in namespace 'std' does not name a type in MinGW mysys prompt

php - 关于根据 IP 地址[字面意思]映射位置的问题

python - 如何在字典中使用 reduce

C++ 将字节写入串行流

c++ - cocos2d-x 中的渲染循环