Inorder Successor in BST II Problem
Description
LeetCode Problem 510.
Given a node in a binary search tree, return the in-order successor of that node in the BST. If that node has no in-order successor, return null.
The successor of a node is the node with the smallest key greater than node.val.
You will have direct access to the node but not to the root of the tree. Each node will have a reference to its parent node. Below is the definition for Node:
class Node {
public int val;
public Node left;
public Node right;
public Node parent;
}
Example 1:
Input: tree = [2,1,3], node = 1
Output: 2
Explanation: 1's in-order successor node is 2. Note that both the node and the return value is of Node type.
Example 2:
Input: tree = [5,3,6,2,4,null,null,1], node = 6
Output: null
Explanation: There is no in-order successor of the current node, so the answer is null.
Constraints:
- The number of nodes in the tree is in the range
[1, 10^4]. -10^5 <= Node.val <= 10^5- All Nodes will have unique values.
Follow up: Could you solve it without looking up any of the node's values?
Solution
Approach: Right Subtree or Climb Up
In an in-order traversal, a node is visited after its whole left subtree and before its right subtree. So the next node after node depends on whether it has a right child:
- It has a right subtree. The successor is the first node visited in that subtree, which is its leftmost node: go right once, then left as far as possible.
- It has no right subtree. Then
nodeis the last node of some subtree, and the traversal goes back up. While we come up from a right child, that parent was already visited before us, so keep climbing. The first time we come up from a left child, that parent is visited next: it is the successor. If we climb past the root without that happening,nodewas the largest value and the answer isnull.
For Example 1, node 1 has no right child and is the left child of 2, so the answer is 2. In Example 2, node 6 has no right child and is the right child of the root 5; climbing past the root gives null.
This compares only pointers, never values, which also answers the follow-up. The tricky case is the climb: checking node.parent.right == node (rather than comparing values) is what tells us which side we came from.
Complexity: O(h) time, where h is the height of the tree: we walk down or up one path. O(1) extra space.
class Solution:
def inorderSuccessor(self, node: 'Node') -> 'Optional[Node]':
if node.right:
# the leftmost node of the right subtree
node = node.right
while node.left:
node = node.left
return node
# climb while we come from a right child; the first parent we reach
# from its left side is the successor (None if we pass the root)
while node.parent and node.parent.right is node:
node = node.parent
return node.parent