mediumTreeTrees

Kth Smallest Element in a BST

mediumTime: O(H + k)Space: O(H)

Recognize the pattern

find kth smallest in BSTin-order traversal gives sorted orderearly termination

Brute force idea

If you approach Kth Smallest Element in a BST in the most literal way possible, you get this: Collect all elements via in-order traversal, return the kth. Visits every node even if k is 1. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

Better approach

The real unlock in Kth Smallest Element in a BST comes when you notice this: In-order traversal with a counter: visit left, decrement k, if k = 0 return current value, else visit right. Stops as soon as the kth element is found. on average. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

At the center of Kth Smallest Element in a BST is one steady idea: In-order traversal of a BST visits nodes in ascending order. The kth node visited is the kth smallest. Counting lets you stop early without visiting all n nodes. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

A common way to get lost in Kth Smallest Element in a BST is this: Not stopping early — in-order traversal visits all nodes if you don't break when k reaches 0. Use iterative traversal with a stack for easy early termination. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Trees Pattern