# Inorder Predecessor and Successor in Binary Search Tree

Objective: Given a Binary Search Tree, Find predecessor and Successor of a given node.

What is Predecessor and Successor :

When you do the inorder traversal of a binary tree, the neighbors of given node are called Predecessor(the node lies behind of given node) and Successor (the node lies ahead of given node).

Example:

Approach:

Say you have to find the inorder predecessor and successor node 15.

• First compare the 15 with root (25 here).
• 25>15 => successor = 25, make recursive call to root.left.(Why do we do it , is explained at step 3).
• New root which is = 15, now stop making recursive calls.
• Now successor will be the left most node in right subtree of which has the root 18 here. So the left most element and successor will be 19. (What if 15 doesn’t have a right subtree, then successor of 15 will be the parent of it, and that is why we set parent as successor in step1).
• Now predecessor will be the right most node in left subtree which has the root 10 here. but 10 doesn’t have right child.
• For the same reason when node<root then make predecessor = root and make a recursive call to the root.right.

Complete Code:

Output:

```Inorder Successor of 10 is : 13 and predecessor is : 7
Inorder Successor of 30 is : 35 and predecessor is : 25
```

__________________________________________________
Top Companies Interview Questions..-

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

### 4 Responses

1. Sumeet Wilkhu says:

I think your “BST” example and approach demonstration is partially incorrect. The node 19 cannot be left child of 18 as 19 is obviously greater than 18. This violates the basic principle of binary search tree where left child should always be less than or equal to parent and right child should be greater than parent. I would suggest you to replace 19 with 17 and the successor for 15 then becomes 17, otherwise, if right sub-tree doesn’t exist, the successor for 15 becomes 25. Please correct that. Thank you.

2. abhineet kapil says:

Very well Explained.

But minor correction as @sumeet_wilkhu:disqus pointed out.

3. abhineet kapil says:

What should be the value of successor for the element 35 (as per the tree created in main method) ? Since 35 comes last as per in-order traversal, shouldn’t its successor be null ?

Below is the code output :

In-order Successor of 35 is : 20 and predecessor is : 30

4. Anand Kumar says:

Simple solution in java for Inorder Predecessor and Successor in Binary Search Tree – https://javadiscover.blogspot.com/2018/06/inorder-predecessor-and-successor-of.html

This site uses Akismet to reduce spam. Learn how your comment data is processed.