我将下面的代码写到BST中 count 个大于给定KEY的节点数:
int Tree::findNumbersThatBiggerThanKey(int key){
return PrivateFindNumbersThatBiggerThanKey(key, this->rootNode);
}
int Tree::PrivateFindNumbersThatBiggerThanKey(int key, Node* start) {
if (!start)
return 0;
if (start->key > key)
return 1 + this->PrivateFindNumbersThatBiggerThanKey(key, start->leftNode) +
this->PrivateFindNumbersThatBiggerThanKey(key, start->rightNode);
else if (start->key < key)
return this->PrivateFindNumbersThatBiggerThanKey(key, start->rightNode);
else /*start->key > key*/
return this->PrivateFindNumbersThatBiggerThanKey(key, start->leftNode);
}
这是我的主要爱好
int main() {
int TreeKeys[16] = { 50, 76, 21, 4, 32, 64, 15, 52, 14, 100, 83, 2, 3, 70, 87, 80 };
Tree myBst;
cout << "Printing the three Inorder before adding numbers: \n";
myBst.printInorder();
for (int i = 0; i < 16; i++) {
myBst.AddLeaf(TreeKeys[i]);
}
cout << "Printing the three Inorder after adding numbers: \n";
myBst.printInorder();
int key = 2;
cout << "\n\nNumber of nodes that are bigger than "<<key<<" : " <<
myBst.findNumbersThatBiggerThanKey(key);
return 0;
}
Inroder打印效果很好:
Printing the three Inorder after adding numbers:
2 3 4 14 15 21 32 50 52 64 70 76 80 83 87 100
但是当我搜索大于“ 2”的节点数时,我得到14个错误的值(而不是15个):
Number of nodes that are bigger than 2 : 14
当我搜索大于“ 1”的节点数时,我得到16个正确的结果(对于其他任何数字我也得到正确的结果):
Number of nodes that are bigger than 1 : 16
我是递归的学生和新手,我很高兴为您解释为什么发生这种情况以及如何解决它。
答案 0 :(得分:3)
您的else
不正确,它的条件是start->key == key
,应与start->key < key
一样对待
因此将其重写为
else
return this->PrivateFindNumbersThatBiggerThanKey(key, start->rightNode);
或仅将其与start->key < key
答案 1 :(得分:1)
由于您未提供MCVE,因此我无法处理您的代码。这样做的一般方法是这样的:
int Tree::PrivateFindNumbersThatBiggerThanKey(int key, Node* node)
{
if (node == null)
{
return 0;
}
int countLeft = PrivateFindNumbersThatBiggerThanKey(node->leftNode, key);
int countRight = PrivateFindNumbersThatBiggerThanKey(node->rightNode, key);
return (node->key > k ? 1 : 0) + countLeft + countRight;
}