I have a simple digital tree defined as below:
class DTN {
public:
DTN () :
is_word(false), word_to_here(""), children()
{}
DTN (bool iw, std::string wth) :
is_word(iw), word_to_here(wth), children()
{}
bool is_word;
std::string word_to_here;
Map<char,DTN> children;
};
I am having problem to define a function called longest_word (const DTN& dtn) which is suppose to return the longest word in the digital tree with iterator and recursion, shown as follow:
std::string longest_word (const DTN& dtn) {
std::string lw = dtn.word_to_here;
for(auto s:dtn.children){
if(s.second.is_word && lw.length()<s.second.word_to_here.length()){
lw = longest_word(s.second);
}
longest_word(s.second);
}
return lw;
}
Assume we have three words in a digital tree DTN: (ante, anteater, anthebellum), and calling the longest_word(DTN) will give me an empty string "" instead of "anthebellum". Can someone please point out what I did wrong in the longest_word function? With actual code will be appreciated because my English is not good, codes are easier for me to understand. Thanks in advance.
The algorithm for longest_word is completely wrong. You should inspect all children longest_words and return the one which is longer. You cannot return before the loop on children is complete. Notice that your algorithm will always return on first children. I don't even understand why you check for a complete word there...
I could try to write the correct code but I feel it is not useful to you. My suggestion is to get back to simplest algorithms like finding the maximum number in a list of integers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.