Binary Search Trees Using the ordering
397. Inorder Successor in BST
You are given root, the root node of a binary search tree, and one of its nodes, p. Return the in-order
successor of p: the node with the smallest value greater than p.val. If no value in the tree is greater
than p.val, return null.
In a binary search tree, every value in a node's left subtree is smaller than the node's value, and every
value in its right subtree is larger. The values in the tree are distinct. The name comes from the in-order
walk (left subtree, node, right subtree), which visits the values from smallest to largest. The successor is
the node that walk visits right after p.
Return a node of the tree itself, not a new node with the same value. The nodes have no link to their parent.
The examples write a tree level by level, from left to right, with null where a child is missing. So
root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The
missing children after the last node are left out. p is written as the value it holds, and the output
shows the value of the node you return, or null.
Example 1
Input: root = [50, 30, 70, 20, 40, 60, 80, null, 25, 35, 45, null, 65]
p = 45
50Explanation: The values larger than 45 are 50, 60, 65, 70 and 80. The smallest of them is 50, the root, three levels above 45.
Example 2
Input: root = [50, 30, 70, 20, 40, 60, 80, null, 25, 35, 45, null, 65]
p = 30
35Explanation: The right child of 30 is 40, but 35, the left child of 40, is smaller. No other value lies between 30 and 35.
Example 3
Input: root = [0, -1000000000, 1000000000], p = 1000000000
nullExplanation: p holds the largest value in the tree, so no node comes after it.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109- The tree has at most 1000 levels.
- The tree is a binary search tree, and its values are distinct.
pis a node of the tree.
Clarifying questions
What you would ask an interviewer before writing any code.