Kth smallest element in a BST
An inorder walk visits BST keys in sorted order, so stop as soon as the kth one is seen.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Inorder traversal of a BST (left, node, right) produces keys in ascending order. Using an explicit stack instead of recursion, push every node while walking left, then pop one at a time; each pop is the next smallest key not yet seen. Count pops, and the moment the count reaches k, that popped node holds the answer, with no need to keep going.
Code
public static int KthSmallest(TreeNode root, int k) {
var stack = new Stack<TreeNode>();
TreeNode node = root;
while (node != null || stack.Count > 0) {
while (node != null) { stack.Push(node); node = node.left; }
node = stack.Pop();
if (--k == 0) return node.val;
node = node.right;
}
return -1;
}static int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode node = root;
while (node != null || !stack.isEmpty()) {
while (node != null) { stack.push(node); node = node.left; }
node = stack.pop();
if (--k == 0) return node.val;
node = node.right;
}
return -1;
}int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> st;
TreeNode* node = root;
while (node != nullptr || !st.empty()) {
while (node != nullptr) { st.push(node); node = node->left; }
node = st.top(); st.pop();
if (--k == 0) return node->val;
node = node->right;
}
return -1;
}def kth_smallest(root: TreeNode | None, k: int) -> int:
stack = []
node = root
while node is not None or stack:
while node is not None: stack.append(node); node = node.left
node = stack.pop()
k -= 1
if k == 0: return node.val
node = node.right
return -1Tips
- Because the walk stops at k, this costs O(h + k) rather than a full O(n) inorder traversal followed by indexing.
In the .NET library
Augmenting each node with the size of its subtree turns this into an O(h) lookup with no traversal at all, the trick behind an order-statistics tree.