【发布时间】:2021-07-17 16:21:57
【问题描述】:
假设一个函数similarity() 接受两个字符串作为参数。如果两个字符串相似,则返回接近 1 的数字,否则返回接近 0 的数字。
到目前为止,我有一个二叉树,其中每个节点都包含一个字符串作为数据。我想创建一个函数,该函数将逐个节点浏览该树并返回相似度最高的单词。
尝试:
使用@AshutoshRaghuwanshi 的答案,我得到了
void Tree::traverse(Node* rootNode, float& score, std::string& bestMatch, std::string& word)
{
if(rootNode == nullptr) return;
if(similarity(rootNode->data, word)>score){
score = similarity(rootNode->data, word);
bestMatch = rootNode->data;
}
traverse(rootNode->left, score, bestMatch, word);
traverse(rootNode->right, score, bestMatch, word);
}
std::string Tree::browseTree(const std::string& word) const{
if(isEmpty()){
throw std::invalid_argument("The tree is empty!");
}
Node * currentNode = root;
float score=0;
std::string bestMatch;
traverse(currentNode->left, score, bestMatch, word);
traverse(currentNode->right, score, bestMatch, word);
if(score>.90){
return bestMatch;
}else{
throw std::invalid_argument("Word not found");
}
}
似乎效果不太好?我哪里错了?
【问题讨论】:
-
提示,如果你的函数返回“banana”这个词的 0.4 和“bandana”这个词的 0.45,你如何决定哪一个是更好的匹配?写一行代码就可以做到这一点。
-
现在是有趣的部分。假设
banana是左子树上的最佳选择,bandana是右子树上的最佳选择,程序应该怎么做才能找到整体上的最佳选择?不用等,有人已经在答案中泄露了所有秘密...... -
有一些错误,但没有什么是无法修复的。
-
请详细说明“似乎效果不佳?”因为这是唯一决定正确解决方案的部分。
标签: c++ recursion binary-tree traversal