在c++中使用按顺序遍历的BST中节点的秩
Rank of a node in BST using in-order traversal in c++
我一直在追踪BST中节点的秩。我得到了一个void函数,它接受一个元素,并使用递归找到节点的秩
我按以下顺序插入节点:12、3、7、4、11、17、15、9。我的问题是,每当我找到匹配项时,递归就不会停止!这是我的算法:
template <class Comparable>
void AugmentedBinarySearchTree<Comparable>::
Rank(const Comparable & x, BinaryNode<Comparable> *t, int *nodesVisited) const
{
// x is the element I am looking for
// t is the root
if (t->left != NULL)
{
Rank(x, t->left, nodesVisited);
if(t->left->element == x)
return;
}
cout << "element " << t->element << ", x " << x << ", nodesVisited "<< *nodesVisited << endl;
if (x == t->element)
{
cout << "found the node " << endl;
return ; // exiting the recursion, nodesVisited will be the rank
// nodesVisited starts counting from 1
}
++(*nodesVisited); // incrementing the count
if (t->right != NULL)
{
Rank(x, t->right, nodesVisited);
}
}
当我做Rank(3)时,它是有效的,但当我做Rank(4)时,递归不会停止,我得到了不同的结果:
element 3, x 4, nodesVisited 1
element 4, x 4, nodesVisited 2
found the node
element 12, x 4, nodesVisited 2
element 15, x 4, nodesVisited 3
element 17, x 4, nodesVisited 4
RANK: 5
每当我找到匹配项时,如何停止递归?
如果在左侧子节点中找到该项,则终止递归
如果在左侧子树中找到它,则需要停止。
像这样的事情可能会起作用(正如你所说,我修改了它以返回等级)
在我看来,使用"null"基本情况通常会导致更简单的树递归
(顺便说一句,完全未经测试的代码。可能有错误。)
int Rank(const Comparable & x, const BinaryNode<Comparable> *t) const
{
int rank = 0;
return FindRank(x, t, &rank) ? rank : -1;
}
// Returns 'true' if and only if the node was found in 't'.
bool FindRank(const Comparable & x, const BinaryNode<Comparable> *t, int* nodesVisited) const
{
if (t == nullptr)
{
return false;
}
if (FindRank(x, t->left, nodesVisited))
{
return true;
}
*nodesVisited += 1;
return t->element == x || FindRank(x, t->right, nodesVisited);
}
相关文章:
- 比较C++中两个BST的节点
- 递归函数,用于计算 BST 中具有两个子节点的节点数
- 检查BST中每个节点的平衡因子并将其存储在节点中
- 删除BST节点:三重故障
- 如何在给定特定节点的BST中找到直接较大的元素
- 为什么我不能将从我的 BST 获取的这个节点推送到这个堆栈中?
- 在BST堆中删除节点免错误
- 如何结合findMin()和delete()来删除BST中的最小节点
- C bST删除节点会破坏排序算法
- 从BST删除节点时出错
- 在 BST 中插入节点时出现逻辑错误
- 递归地将 1 添加到 BST 中的所有节点,但具有最小数据的节点除外
- BST 节点删除 - 指针未正确删除
- 将节点插入 BST
- 删除BST中的节点
- 找到任何节点的BST高度
- 如何在BST中从最高到最低打印特定范围内的数字,访问的节点最少
- 从 BST 中删除唯一的节点
- 计算 BST 节点移除的时间复杂度
- 删除BST节点导致seg故障.处理步骤