打印出使用地图实现的Trie中的所有单词

Print out all words in a Trie implemented with a map

本文关键字:Trie 单词 实现 地图 打印      更新时间:2023-10-16

我有一个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中的所有单词打印为数组,而不是地图。

这是一个深度优先的递归遍历。最好不要使用原始指针,但我在这里这样做是因为你问了,我喜欢你。我没有删除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

我假设您想通过使用映射来浪费比每个节点中的 26 插槽数组更少的内存?但是看到映射的初始构建成本相当高,您可能希望对所有节点使用相互映射,而不是在每个节点中存储一个。