We leverage the fact that an in-order traversal of a Binary Search Tree (BST) visits nodes in ascending order.
The provided k parameter acts as a mutable downward counter indicating how many more nodes remain before we reach
the kth smallest element. Each time we “visit” a node (i.e., process it between its left and right recursive calls),
we decrement k. When k reaches 0 immediately after visiting a node, that node is the
kth smallest. If a non-null result is returned from the left subtree, it means the kth smallest element was found there,
so we return it immediately, allowing the result value to naturally propagate upward through the recursion stack after it is found.
🔧 Traversal Logic
-
Base case: If the current
nodeisnull, returnnull— signaling that no result was found in this branch. - Go left first: Recursively traverse the left subtree to enumerate all smaller values (if any).
-
Bubble up early if found on the left: If the left recursion returns a non-
nullvalue, it means the kth smallest element was already found there, so we return it immediately — skipping the current node and its right subtree. - Visit node: Otherwise, process the current node and decrement
k. -
Result-found condition: When
k == 0after visiting a node, we’ve found the kth smallest element. Return it immediately — the result propagates up the recursion stack. - Then go right: If the kth element wasn’t found in the left subtree or the current node, we recurse into the right subtree to continue counting larger elements in ascending order. The recursive call will inevitably return the correct result, so we can unconditionally return its value upward.
🧠 Correctness Intuition
In a BST, left-subtree values are smaller and right-subtree values are larger. Thus, in-order traversal yields a strictly
increasing sequence. Counting down k at each visit aligns with the node’s rank in that order — when
k hits 0, we’re at the kth smallest. Early return after the left recursion (when it already
found the answer) preserves correctness and avoids unnecessary work.
🧭 Result Semantics
When k reaches 0 upon visiting a node, that node’s value is the kth smallest. The function
returns it immediately, and the value is bubbled up through recursive returns to the caller.