285. Inorder Successor in BST
Problem
Given a BST and one of its nodes p, return the in-order successor of p (the node with the smallest value greater than p.val), or null if p holds the largest value.
Example: [5,3,6,2,4,null,null,1], p = 6 → null; p = 4 → 5
Problem (Premium): given a BST and one of its nodes p, return the node with the smallest key greater than p.val, or null.
No in-order traversal needed: walk down from the root. Whenever p.val < node.val, this node is a candidate (it's bigger than p) — remember it and go left looking for a smaller one; otherwise go right.
Complexity: O(h) time, O(1) space.
class Solution:
def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> Optional[TreeNode]:
succ = None
while root:
if p.val < root.val:
succ, root = root, root.left
else:
root = root.right
return succ
t = make_tree([2, 1, 3])
assert Solution().inorderSuccessor(t, find_node(t, 1)).val == 2
t = make_tree([5, 3, 6, 2, 4, None, None, 1])
assert Solution().inorderSuccessor(t, find_node(t, 6)) is None
assert Solution().inorderSuccessor(t, find_node(t, 4)).val == 5
assert Solution().inorderSuccessor(t, find_node(t, 1)).val == 2
assert Solution().inorderSuccessor(t, find_node(t, 3)).val == 4
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
TreeNode succ = null;
while (root != null) {
if (p.val < root.val) { succ = root; root = root.left; }
else root = root.right;
}
return succ;
}
}
func inorderSuccessor(root *TreeNode, p *TreeNode) *TreeNode {
var succ *TreeNode
for root != nil {
if p.Val < root.Val { // root is a candidate; look for a smaller one on the left
succ, root = root, root.Left
} else {
root = root.Right
}
}
return succ
}