Kth Smallest in BST
Medium
TreeBSTIn-order
Problem
Given the root of a BST and an integer k, return the kth smallest value (1-indexed).
Example 1
Input: root=[3,1,4,null,2], k=1
Output: 1
Example 2
Input: root=[5,3,6,2,4,null,null,1], k=3
Output: 3
Constraints
- 1 ≤ k ≤ nodes
- 1 ≤ nodes ≤ 10⁴
Approach — Tree Traversal
This is a Tree Traversal problem. The idea: traverse the tree — DFS recursively, or BFS level by level — and combine the results from each subtree. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time.
Solution code
Python
class Solution:
def kthSmallest(self, root, k):
stack = []
cur = root
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
k -= 1
if k == 0:
return cur.val
cur = cur.right
Java
import java.util.ArrayDeque;
import java.util.Deque;
class Solution {
public int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new ArrayDeque<>();
while (root != null || !stack.isEmpty()) {
while (root != null) { stack.push(root); root = root.left; }
root = stack.pop();
if (--k == 0) return root.val;
root = root.right;
}
return -1;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Kth Smallest in BST interactively → ← All solutions