0
我想为我的树数据结构实现一个搜索功能。我很困惑如何正确地实现这一点,因为我现在认为我的逻辑似乎是正确的......尽管我仍然是这方面的初学者。如果有人可以看看我的功能,并建议在哪里改进,那将不胜感激。主要接受大型文件,然后在其中搜索单词以基本测试功能。现在它对于应该在特定对象中的单词返回false。我找到/添加功能无法正常工作
例如错误消息
Error: jean-pierre is not in the spellcheck and it should have been
搜索功能:
//looks up the word in the SpellCheck object. If it is in the SpellCheck object,true is returned.
//You can assume that the word will be all lower case.
bool lookup(const string& word) const {
if (!root_) {
return false;
}
Node* curr = root_;
if (word[0] == '\0') {
return curr->isTerminal_ == true;
}
for (int i = 0; i < word.length(); i++)
{
int idx = curr->getIndex(word[i]);
if (idx < 0 || idx >= 26){
return false;
}
// Search top level for node that
// matches first character in key
if (curr->children_[idx] == nullptr) {
return false;
}
curr = curr->children_[idx];
}
return curr->isTerminal_ == true;
}
节点结构:
struct Node {
bool isTerminal_;
char ch_;
Node* children_[26];
Node(char c = '\0') {
isTerminal_ = false;
ch_ = c;
for (int i = 0; i < 26; i++) {
children_[i] = nullptr;
}
}
//given lower case alphabetic charachters ch, returns
//the associated index 'a' --> 0, 'b' --> 1...'z' --> 25
int getIndex(char ch) {
return ch - 'a';
}
};
Node* root_;
您的查找方法看起来还好。请提供您的插入功能 –
插入功能在测试时正常工作。 – user7795742
然后用放置断点调试你的代码。 –