177. Inorder successor and predecessor in BST

Given the root node of a binary search tree (BST) and an integer key. Return the Inorder predecessor and successor of the given key from the provided BST.

Note: key will always present in given BST.

If predecessor or successor is missing then return -1.

Example 1:

Input : root = [5, 2, 10, 1, 4, 7, 12] , key = 10

Output : [7, 12]

Explanation :

Example 2:

Input : root = [5, 2, 10, 1, 4, 7, 12] , key = 12

Output : [10, -1]

Explanation :

Now Your Turn!

Pick the correct output for the given input

Input : root = [5, 2, 10, 1, 4, 7, 12] , key = 1

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= Number of Nodes <= 104
  • 1 <= Node.val <= 105
  • All the values Node.val are unique.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int val) : data(val) , left(nullptr) , right(nullptr) {}
* };
**/
 
class Solution{
public:
vector<int> succPredBST(TreeNode* root,int key){
//your code goes here
}
};
Test Case

Input:

Key
Root