So I'm trying to implement a TREE_SUCCESSOR(X) function for BST where X is the key of the node that I'm trying to find the successor of. So far I have this:
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;
}
}
My problem is in the main function:
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
{
????
}
}
I want to find out how to traverse the BST to the node of the BST till the key = num
. For example, if the tree had nodes 3,4,5
then TREE_SUCCESSOR(4)
, should return 5
. How would I do this??
EDIT
So I decided used a TREE_SEARCH(key)
that would find the node with a certain key and return it... and then pass that node into TREE_SUCCESSOR(X)
.