Case 1: Target node has a right child
If the target node p
has a right child, then the inorder successor is the leftmost node in the right subtree. This is because, in an in-order traversal, we visit the left subtree, then the node, and then the right subtree. So, the smallest value in the right subtree will be the next one in sequence.
Example: In the tree [2, 4, 6, 8], if p = 4
and 4 has a right child 6, and 6 in turn has a left child 5, then the successor is 5 (the leftmost in the right subtree).
Case 2: Target node does not have a right child
If the target node p
does not have a right child, then we have to look upward in the tree. The inorder successor is one of the ancestors — the first one whose value is greater than p.val
. This works because once we go left from such an ancestor to reach p
, that ancestor will be the next node visited in the in-order traversal.
We traverse from the root, and whenever p.val < current.val
, we store the current node as a potential successor and move to the left child, narrowing down to a closer successor. If p.val >= current.val
, we move right. Finally, the stored successor (if any) is our answer.
Case 3: Target node is the largest in the tree
When p
is the rightmost node in the BST, there is no successor because no node has a value greater than p
. In such a case, the answer is null
.
This is common when the tree is skewed to the right or when the value of p
is the maximum.
Case 4: Tree is empty or p
is null
In this case, there is no node to compare or traverse. So, we simply return null
. This is a boundary case, but important for robustness of your solution.
Case 5: Tree has only one node
If the tree contains only one node and that node is p
, there’s no possibility for an inorder successor. The result is null
.
This case helps us understand that successor depends on the tree structure, not just the node value.