Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Trees

Kth Smallest Element In a Bst

MEDIUM✓ CHIP-TIMEDLC #230 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Find the k-th smallest value stored in a BST — the tree's shape encodes sorted order for free, if you traverse it the right way.

A binary search tree and a rank k arrive together, and the task is naming which value sits at position k when every node's value is listed in ascending order.

BSTs already encode sorted order in their shape — the way you walk it decides whether you're rediscovering that order the hard way or reading it off for free.

k always falls inside the number of nodes present, so the only real question is finding the value that lands at that rank and returning it.

  • k always falls within the tree's actual node count
  • tree sizes reach into the tens of thousands
  • values are unique across the tree, consistent with BST ordering
  • k is 1-indexed — k=1 means the smallest value
EX 01
root = [3, 1, 4] · k = 1
→ 1
smallest
EX 02
root = [3, 1, 4] · k = 2
→ 3
middle
EX 03
root = [3, 1, 4] · k = 3
→ 4
largest

The hintstake only what you need

HINT 1 THE NUDGE

A BST's inorder traversal visits values in ascending sorted order — that fact alone solves most of this problem.

HINT 2 THE STRUCTURE

You don't need every value, just the k-th one. What lets a traversal stop the instant it produces the k-th value, instead of finishing the whole tree?

HINT 3 ONE STEP FROM THE ANSWER

Iterative inorder with an explicit stack: push left spines, pop, count each pop — the k-th pop's value is the answer, and the stack lets you return immediately.

Coach's boardthe pattern, step by step

STOP AT THE K-TH POPPATTERN · STOP AT THE K-TH POProot = [5, 3, 8, 1, 4, 7, 9] · k = 4
STACK
— empty —
STEP 1

Push every left child down to the bottom — the stack's TOP is always the next-smallest unvisited value. Target k=4.

STEP 1 / 7 · ← → WORK TOO

The splitstwo paces, two languages

grind/kth-smallest-element-in-a-bst.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
        stack = []
        node = root
        count = 0
        while stack or node:
            while node:
                stack.append(node)
                node = node.left
            node = stack.pop()
            count += 1
            if count == k:
                return node.val
            node = node.right
        return -1
TIME O(H + K)SPACE O(H)PYTHON · RACE PACE · 15 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED