SDE & MLE Prep

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