Given the root of a binary search tree and an integer k, return the kth smallest value (1-indexed) of all the values in the tree.
Input: root = [3,1,4,null,2], k = 1
Output: 1
Tree:
3
/ \
1 4
\
2
In-order: [1, 2, 3, 4]
1st smallest = 1
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
Tree:
5
/ \
3 6
/ \
2 4
/
1
In-order: [1, 2, 3, 4, 5, 6]
3rd smallest = 3
Key BST Property: In-order traversal visits nodes in sorted order!
For BST, in-order traversal produces: left → root → right = sorted sequence.
To find kth smallest:
We can optimize by stopping early once we reach k nodes.
This is an In-order Traversal problem with:
Initialize: counter = 0, result = None
In-order Traversal:
inorder(node):
if not node: return
inorder(node.left) # Visit left
counter++ # Process current
if counter == k:
result = node.val
return
inorder(node.right) # Visit right
Return result
Optimization: Stop recursion once k is reached (no need to visit remaining nodes).
stack = []
current = root
count = 0
while current or stack:
while current:
stack.append(current)
current = current.left
current = stack.pop()
count += 1
if count == k:
return current.val
current = current.right
Time: O(h + k) where h = height
Space: O(h) recursion stack
Optimized approach is better when k is much smaller than n.
1class TreeNode {
2 int val;
3 TreeNode left;
4 TreeNode right;
5 TreeNode() {}
6 TreeNode(int val) { this.val = val; }
7 TreeNode(int val, TreeNode left, TreeNode right) {
8 this.val = val;
9 this.left = left;
10 this.right = right;
11 }
12}
13
14class Solution {
15 private int count = 0;
16 private int result = 0;
17
18 public int kthSmallest(TreeNode root, int k) {
19 inorder(root, k);
20 return result;
21 }
22
23 private void inorder(TreeNode node, int k) {
24 if (node == null || count >= k) {
25 return;
26 }
27
28 // Visit left subtree
29 inorder(node.left, k);
30
31 // Process current node
32 count++;
33 if (count == k) {
34 result = node.val;
35 return;
36 }
37
38 // Visit right subtree
39 inorder(node.right, k);
40 }
41}
42