Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Predecessor and Successor In BST
MEDIUM
25 mins
15 upvotes
Trees
Binary Search Trees
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Trees
-
-
Binary Search Trees
-
-
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
Linked List
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
Arrays
-
-
SQL
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Predecessor and Successor In BST

Contributed by
Ankush Gupta
Medium
yellow-spark
0/80
Avg time to solve 25 mins
Success Rate 65 %
Share
15 upvotes

Problem Statement

Given a binary search tree of integers containing 'N' nodes. You have also been given an integer X.

Your task is to find the inorder successor and predecessor of the given X. Formally, print an array/list containing the inorder predecessor and successor in the same order.

For Example:
For the BST given below:

alttext

The inorder predecessor of 6 is 4.
The inorder successor of 6 is 7.
The inorder predecessor of 10 is 8.
The inorder successor of 10 is 13.

Note:

If there is no inorder predecessor or successor of 'X', then add -1 to the answer vector in its place.
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1:
1
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
5
Sample Output 1:
2 6

Explanation of the Sample Input 1:

For the given ‘X’ = 5, according to the inorder view, 2 is the parent of the left subtree and 6 is the parent of the right subtree, hence 2 and 6 are inorder predecessors and successor respectively.
Sample Input 2:
2
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
6
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
2
Sample Output 2:
5 7
-1 5
Reset Code
Full screen
Auto
copy-code
Console