Kth Smallest Element in a BST (LeetCode 230): Solution and Explanation
Given the root of a binary search tree and an integer k, return the kth smallest value stored in the tree, counting from 1. The tree has at least k nodes, so the answer always exists.
Watch it run step by step
Try your own input and write the code →Intuition
Without using the BST property, you could collect every value, sort them, and index position k minus 1. That costs O(n log n) and throws away the most useful fact about the input: a binary search tree is already sorted, as long as you read it in the right order.
Inorder traversal visits the left subtree, then the node, then the right subtree. In a BST that produces the values in ascending order. So the kth node visited by an inorder traversal is exactly the kth smallest value. A recursive inorder that fills an array and returns arr[k - 1] is already O(n), but it still visits the whole tree even when k is 1.
An iterative inorder traversal with an explicit stack lets you stop the moment you reach the kth node. You push nodes while walking as far left as possible, because the leftmost node is the smallest. Popping a node means everything smaller than it has already been handled, so you count it. If the count reaches k you are done; otherwise you move into its right subtree, which holds the next larger values, and repeat. Only the nodes on the path to the answer plus the k visited ones are ever touched.
Approach: Iterative inorder traversal with early exit
- Initialize an empty
stackand setcurr = root. - While the stack is non-empty or
curris not None, first walk left: pushcurrand move tocurr.leftuntilcurris None. - Pop the top node. It is the smallest value not yet counted.
- Decrement
k. Ifkreaches 0, return this node's value. - Otherwise set
currto the popped node's right child so the next round explores the values just larger than it.
Step-by-step example
root = [3,1,4,null,2], k = 3
- Walk left from 3: push 3, push 1, and stop because 1 has no left child. The stack is [3, 1].
- Pop 1 and decrement
kto 2. Move to its right child 2. - Push 2. It has no left child, so pop it right away and decrement
kto 1. Its right child is None. - With
currNone, pop 3 from the stack and decrementkto 0. - Since
kis 0, return 3. Node 4 is never visited.
Code: Python, Java, C++
1class Solution:
2 def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
3 stack = []
4 curr = root
5
6 while stack or curr:
7 while curr:
8 stack.append(curr)
9 curr = curr.left
10 curr = stack.pop()
11 k -= 1
12 if k == 0:
13 return curr.val
14 curr = curr.right1class Solution {
2 public int kthSmallest(TreeNode root, int k) {
3 Stack<TreeNode> stack = new Stack<>();
4 TreeNode curr = root;
5
6 while (!stack.isEmpty() || curr != null) {
7 while (curr != null) {
8 stack.push(curr);
9 curr = curr.left;
10 }
11 curr = stack.pop();
12 k--;
13 if (k == 0) return curr.val;
14 curr = curr.right;
15 }
16 return 0;
17 }
18}1class Solution {
2public:
3 int kthSmallest(TreeNode* root, int k) {
4 stack<TreeNode*> stack;
5 TreeNode* curr = root;
6
7 while (!stack.empty() || curr) {
8 while (curr) {
9 stack.push(curr);
10 curr = curr->left;
11 }
12 curr = stack.top();
13 stack.pop();
14 k--;
15 if (k == 0) return curr->val;
16 curr = curr->right;
17 }
18 return 0;
19 }
20};Time and space complexity
O(h + k)
Reaching the smallest node costs up to h pushes down the left spine, and after that each of the k pops does amortized constant work. In the worst case this is O(n).
O(h)
The stack holds at most one root-to-leaf path of nodes at a time, so it is bounded by the tree height h.
Other approaches
Recursive inorder into an array (time O(n), space O(n))
Traverse the whole tree inorder, append each value to a list, and return values[k - 1]. It is the easiest version to write but always visits all n nodes and stores them.
Subtree size augmentation (time O(h) per query, space O(n))
Store the size of each node's subtree. At a node, compare k with the left subtree size plus one to decide whether to return, go left, or go right with a reduced k. Building the sizes is O(n) once, but each query then takes O(h), which pays off when the tree changes often and the question is asked repeatedly.
Common mistakes
- Decrementing
kwhile pushing nodes rather than when popping them. Only a popped node has had all smaller values processed. - Forgetting to move
currto the right child after a pop, which either loops forever or skips whole subtrees. - Using preorder or level order. Only inorder visits a BST in sorted order.
- Treating k as zero-based. The problem counts from 1, so the answer is the node where
khits 0 after decrementing.
Frequently asked questions
Why does inorder traversal give sorted order in a BST?
Every value in the left subtree is smaller than the node and every value in the right subtree is larger. Inorder visits left, then node, then right, so it outputs all smaller values before the node and all larger values after it.
What is the time complexity of finding the kth smallest element in a BST?
With an iterative inorder that stops early, it is O(h + k), which is O(n) in the worst case. The space is O(h) for the stack.
How would you handle frequent inserts and deletes with repeated kth smallest queries?
Store the size of each subtree in its node and keep those sizes updated during inserts and deletes. Then you can find the kth smallest by comparing k with left subtree sizes while walking down, in O(h) per query.