c++ - 打印出用 map 实现的 Trie 中的所有单词

标签 c++ data-structures trie

我有一个 TrieNode 类定义如下:

class TrieNode {
public:
    map<char, TrieNode*> children;
    bool isLeaf = false; // if node represents end of word
    int wordCount = 0; // How many times the word appears
    TrieNode();
};

我正在尝试打印出 trie 中的所有单词(最好按字母顺序排列,尽管此时我会接受任何东西)。我一直在尝试实现一个递归解决方案,但我一直没能有一个像样的开始。

编辑:我应该提一下,我研究过的所有其他问题都是关于如何将 trie 中的所有单词打印为数组而不是 map 。

最佳答案

这是一个深度优先的递归遍历。 最好不要使用原始指针,但我在这里这样做是因为你问了,我喜欢你。 我没有删除AddTrie分配的子节点,因为我只是想演示遍历,而不是写一个完整的实现。 所以,如果你使用这个,你需要添加代码来删除它们。

#include <iostream>
#include <map>
#include <string>

class TrieNode {
public:
    std::map<char, TrieNode*> children;
    bool isLeaf = false; // if node represents end of word
    int wordCount = 0; // How many times the word appears
    TrieNode() {}
};

void AddTrie(TrieNode& trie, const char* word) {
    auto c = *(word++);
    auto next = trie.children[c];
    if(!next) { trie.children[c] = next = new TrieNode; }
    if(*word) { AddTrie(*next, word); }
    else      { next->isLeaf = true; }
}

void DumpTrie(const TrieNode& trie, std::string word={}) {
    for(const auto& child : trie.children) {
        const auto next_word = word + child.first;
        if(child.second->isLeaf) { std::cout << next_word << '\n'; }
        DumpTrie(*child.second, next_word);
}   }

int main() {
    TrieNode trie;
    AddTrie(trie, "goodbye");
    AddTrie(trie, "hello");
    AddTrie(trie, "good");
    AddTrie(trie, "goodyear");
    DumpTrie(trie);
}

输出

good
goodbye
goodyear
hello

关于c++ - 打印出用 map 实现的 Trie 中的所有单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43286558/

相关文章:

c# - 如何在 C# 中创建一个特里树

algorithm - 如何在哈希表和Trie(前缀树)之间进行选择?

c++ - 我在 C++ 中的 Trie 程序有逻辑错误

c++ - 在 for 循环中处理复杂的 send recv 消息

algorithm - 这个数据结构的名称是什么?

c# - AutoResetEvent 和多个 Set

c - 普通 C 中类型安全的通用数据结构?

c++ - 调用函数并使用 goto : memory leak? 将其转义

C++11,内存泄漏

c++ - Visual Studio .cu 文件显示语法错误但编译成功