↻one more pass.
Trees · Medium

Kth Smallest Element in a BST: the idea to remember.

Return the kth smallest value in a BST, with k guaranteed valid.

Solve on LeetCode ↗

The core insight

Iteratively traverse inorder using a stack and return the value at the kth visited node.

Why it works

Inorder traversal visits a valid BST in increasing order, so visit rank equals sorted rank.

The mistake to avoid

Descending left does not count a visit. Count only when a node is popped for processing.

Time: O(h + k)Space: O(h)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

int kthSmallest(TreeNode root, int k) {
    Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode current = root;
    while (current != null || !stack.isEmpty()) {
        while (current != null) { stack.push(current); current = current.left; }
        current = stack.pop();
        if (--k == 0) return current.val;
        current = current.right;
    }
    throw new IllegalArgumentException("k is outside the tree");
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.