打印出使用地图实现的Trie中的所有单词
Print out all words in a Trie implemented with a map
我有一个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 插槽数组更少的内存?但是看到映射的初始构建成本相当高,您可能希望对所有节点使用相互映射,而不是在每个节点中存储一个。
相关文章:
- 文本文件中的单词链表
- 在指针的帮助下,文本文件中单词的频率
- 如何根据单词在文本中出现的概率输出单词
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- 如何用for循环在c++中生成单词三角形
- 将数字转换为单词
- 使用if-else将数字转换为单词
- C++-字符串是否包含一个带有简单循环的单词
- 使用单词"not"作为C ++类的名称会导致VS2019错误
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- C++为一串单词添加空格
- 打印出使用地图实现的Trie中的所有单词
- 使用Trie打印所有字典的单词
- 尝试将单词插入 trie 时出现分段错误
- TRIE数据结构中的所有单词
- 为什么这些单词没有包含在我的词典中(c++trie)