节点堆叠如何在C中的trie中工作?

时间:2017-10-31 04:35:32

标签: c struct trie

我一直在努力清楚地了解如何将节点堆叠到根节点中trie. 更具体地说,当创建新节点并以某种方式添加到根节点时。

到目前为止,我能够理解的是有一个结构和一个根节点:

(假设这个特里正在处理单词)

typedef struct trieNode
{
    bool isEndOfWord;
    struct trieNode *children[26];
} trieNode;

// for now let's say all these nodes are initialized for the sake of simplicity
trieNode *root;

如果我要向root添加另一个节点,它会像这样实现吗?

// scan the word character by character (assume word is something like "dog")
for(int i = 0; i < strlen(word); i++)
{
    // if character does not exist, create a new node and point root to it
    if(root->children[word[i] - 'a'] == NULL)
    {
            trieNode *newNode = makeNewNode(); // function to quickly initialize a node (not important for this question though)
            if(i == strlen(word) - 1) newNode->endOfWord = true;
            else root->endOfWord = false;

            // this is where I think I am making my logic error
            root->children[word[i] - 'a'] = newNode;
    }
    else
    {
        // move to a new node
        root = root->children[word[i] - 'a'];
    }
}

这两个陈述 root->children[word[i] - 'a'] = newNode;root = root->children[word[i] - 'a'];使用正确吗?如果没有,我怎么能让他们按照他们的意图去做呢?

0 个答案:

没有答案