Pattern visualizer
Kth Smallest Element in a BST
An inorder traversal of a BST (left, node, right) visits every key in strictly ascending order — that is the ordering invariant paying off directly. So the kth smallest element is simply the kth value that traversal emits, and there is no need to collect all n values first: an explicit stack can walk left as far as possible, pop one node at a time, count down k, and return the instant k reaches zero — skipping every node past the answer. Animated on: root = [5,3,6,2,4,null,null,1], k = 3 — return the kth smallest value in the BST (1-indexed). Expected: 3..
Early-stopping inorder traversal with an explicit stack
Call stack
Call kthSmallest(root, k=3). Point node at the root, 5, with an empty stack. A BST's inorder traversal (left, node, right) visits keys in strictly ascending order, so the kth key it emits is the answer — no sorting needed.
1node <- root2stack <- EMPTY3WHILE node != null OR stack NOT EMPTY:4 WHILE node != null:5 PUSH node TO stack6 node <- node.left7 node <- POP(stack)8 k <- k - 19 IF k = 0:10 RETURN node.val11 node <- node.right
← / → step · space play · Home restart