c++ - 给定键,如何找到 BST 的某个元素?

标签 c++ binary-search-tree

所以我正在尝试为 BST 实现一个 TREE_SUCCESSOR(X) 函数,其中 X 是我试图找到其后继节点的键。到目前为止我有这个:

int BinarySearchTree::TREE_SUCCESSOR(node* x)
{
//i dont need a new node, I just need a pointer/reference to x. 
node* y = NULL;
//node* parent = NULL;
if (x->right != NULL)
{
    return FIND_MIN(x->right);
}
else
{
    y = x->parent; 
    while (y != NULL && x == y->right)
    {
        x = y;
        y = y->parent;
    }
    return y->key; 
}
} 

我的问题出在主要功能上:

int main()
{
BinarySearchTree bst;
int num = 0; 
cout << "Enter number you want to find the successor of: " <<endl; 
cin >> num; 

if(BST.root->key == num)             //if i'm trying to find the successor of the root
   { TREE_SUCCESSOR(BST.root); } 
else
{ 
    while(BST.root->key != num)      //if the user input does not equal the root key value 
    { 
        ???? 
    }
} 

我想知道如何遍历 BST 到 BST 的节点,直到 key = num。例如,如果树有节点 3,4,5,则 TREE_SUCCESSOR(4) 应该返回 5。我该怎么做?

编辑

所以我决定使用 TREE_SEARCH(key) 找到具有特定键的节点并返回它...然后将该节点传递给 TREE_SUCCESSOR(X)

最佳答案

按顺序执行 traversal .

找到元素后继续遍历,下一个元素就是你需要的。

如果您正在寻找根的后继者,您不需要任何特殊情况,但您需要处理元素是遍历中的最后一个元素的情况,即最大的一个。

关于c++ - 给定键,如何找到 BST 的某个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31169253/

相关文章:

c - C 中按字母顺序排序的二叉搜索树?

c++ - 如何计算数字的非空数字和可被3整除的数字

c++ - 将 long 转换为 int 与使用按位 AND 以获得 4 个最低有效字节之间有什么区别?

c++ - 是否保证堆分配的 block 地址不会(隐式地)改变?

C++ 如何生成 10,000 个唯一的随机整数以存储在 BST 中?

c++ - 递归打印二叉搜索树的内容?

c++ - BST 中不清楚的指针错误

c++ - 将字节转换为 char 数组 - 然后再转换回来

c++ - 使用 `Node*` 作为列表的迭代器

python - 删除二进制搜索树python中的节点