Trees & BST · Pattern 9 of 12

Inorder and reverse inorder: kth smallest and largest

Inorder (left, node, right) visits a BST in increasing order; reverse inorder (right, node, left) visits it in decreasing order. Count the nodes as you go and stop at the kth.

1 variation · 1 problem · 2 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Kth smallest or kth largest value in a BST
  • Visit a BST from the largest value down (running sums of greater values)
  • Stop early instead of sorting everything

The template

Reverse Inorder Traversal
// kth largest: right, node, left visits values from the largest down
int remaining, answer;
int kthLargest(TreeNode root, int k) {
    remaining = k; answer = -1;
    reverseInorder(root);
    return answer;
}
void reverseInorder(TreeNode node) {
    if (node == null) return;
    reverseInorder(node.right);
    if (remaining > 0 && --remaining == 0) answer = node.val;        // the kth visit
    if (remaining > 0) reverseInorder(node.left);               // stop once found
}

// kth smallest: iterative inorder, stop at the kth pop
int kthSmallest(TreeNode root, int k) {
    Deque<TreeNode> st = new ArrayDeque<>();
    TreeNode cur = root;
    while (cur != null || !st.isEmpty()) {
        while (cur != null) { st.push(cur); cur = cur.left; }
        cur = st.pop();
        if (--k == 0) return cur.val;
        cur = cur.right;
    }
    return -1;                                             // fewer than k nodes
}

The variations

  1. 1Stop at the kth visit

    Count every visit of an inorder walk and return at the kth. Iterative inorder makes stopping easy: just return from the loop. Reverse the walk for the kth largest.

Mistakes to avoid

  • Collecting the whole inorder list just to read index k: it works, but O(n) space and no early stop.
  • Passing the counter by value in C++ or as a plain argument in Python and JS: each call gets its own copy. Use a reference, a field or a closure.
  • Kth largest with plain inorder needs the size of the tree first; reverse inorder does not.
Next: Build a tree from traversals, and serialize it →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.