在c++中使用按顺序遍历的BST中节点的秩

Rank of a node in BST using in-order traversal in c++

本文关键字:BST 节点 遍历 c++ 顺序      更新时间:2023-10-16

我一直在追踪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);
}