c++ - Print out all words in a Trie implemented with a map -
i have trienode class defined follows:
class trienode { public: map<char, trienode*> children; bool isleaf = false; // if node represents end of word int wordcount = 0; // how many times word appears trienode(); }; i'm trying print out of words in trie (preferably in alphabetical order, although i'd settle @ point). i've been trying implement recursive solution, haven't been able make decent start.
edit: should mention other questions i've looked @ how print words in trie store children array, rather map.
here's depth-first recursive traversal. best not use raw pointers, did here because asked , you. did not delete child nodes allocated addtrie, because wanted demonstrate traversal, rather write entire implementation. so, need add code delete these if use this.
#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 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); } output
good goodbye goodyear hello
Comments
Post a Comment