Return the k-th smallest value (1-indexed) in a binary search tree.
Walk in-order with an explicit stack and stop as soon as the k-th node is popped. There is no need to visit the rest of the tree.
1function kthSmallest(root: TreeNode | null, k: number): number {2const stack: TreeNode[] = [];3let n = root;4while (true) {5while (n) { stack.push(n); n = n.left; }6n = stack.pop()!;7if (--k === 0) return n.val;8n = n.right;9}10}
Start at the root.
Space: play/pause · ←/→: step