【发布时间】:2015-09-19 01:53:18
【问题描述】:
所以我正在尝试为 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)。
【问题讨论】:
-
仅供参考的函数名称不应全部大写。
-
哦。这只是约定吗?
-
AFAIK 这只是一个约定:stackoverflow.com/questions/3799478/…
-
这是惯例,如果你不遵守,每个人都会讨厌你。所有大写字母都用于命名常量。在我使用过的几乎所有编程语言中都是如此。
-
@RobK Lol 我会改变的。事实上我的教授就是这样,所以当我创建不同的方法时,我只是遵循相同的约定。