Reputation: 99
I am learning how to find inorder successor in Binary Search Tree I have learned that:
If right sub-tree of node is not NULL, then successor lies in right sub-tree. Do following.
Go to right sub-tree and return the node with minimum key value in right sub-tree.
If right sub-tree of node is NULL, then successor is one of the ancestors. Do following.
Travel up using the parent pointer until you see a node which is left child of it’s parent. The parent of such a node is the successor.
I did not understand that why if the right subtree is not null we have to return node with the minimum value, and if the right subtree is null we have to find a node which is left child of its parent. And parent of such node is successor.
plz help..this is the key point of this algorithm.
struct node * inOrderSuccessor(struct node *root, struct node *n)
{
// step 1 of the above algorithm
if( n->right != NULL )
return minValue(n->right);
// step 2 of the above algorithm
struct node *p = n->parent;
while(p != NULL && n == p->right)
{
n = p;
p = p->parent;
}
return p;
}
Upvotes: 0
Views: 453
Reputation: 15162
Consider the following tree: 4 2 6 1 3 5
First consider getting the successor of '3', since the right child is null you have to go up the tree to the parent of the first ancestor that is the left child of its parent. Remember that in a binary search tree every left child will be less than the current node and every right child will be greater. By this logic the parent of any left child will be greater than that child.
Now consider getting the successor of '4', first you would go to '6', but since it has a left child any nodes in that left descent tree will be between 4 and 6, the left-most child of the immediate right child will be the direct successor to such a node.
Upvotes: 0