Kth Smallest Element in a BST
Medium · Trees
Jump to codeGiven a BST with distinct values and a valid one-based rank k, return its kth smallest value.
Examples
Example 1
root = [3,1,4,null,2] k = 1
Output: 1
Example 2
root = [5,3,6,2,4,null,null,1] k = 3
Output: 3
Constraints
- 1 <= k <= The number of nodes in the tree <= 1000
- 0 <= Node.val <= 1000
Function contract
Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.
Need a hint?
In-order traversal of a BST produces sorted values.
Asked in real interviews
Candidates reported versions of Kth Smallest Element in a BST from these company interviews. Some company questions are locked and open with Premium or XP.
- Find the Kth Smallest Value in a Binary Search TreeAmazon
- Find Kth Smallest in BSTUber
- Find the Kth Smallest Value in a Binary Search TreeSalesforce
Solution approach
Use a stack to descend to the leftmost unvisited node. Pop and count one visited value, returning when the count reaches k. Then traverse its right subtree by pushing that subtree’s left spine. Stop early rather than materializing every value.
Complexity
O(h + k) time and O(h) space.
Python reference solution
def kthSmallest(root, k):
stack = []
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
k -= 1
if k == 0:
return root.val
root = root.right
JavaScript solution
function kthSmallest(root, k) {
const stack = [];
while (root || stack.length) {
while (root) { stack.push(root); root = root.left; }
root = stack.pop();
if (--k === 0) return root.val;
root = root.right;
}
return -1;
}
Java solution
import java.util.*;
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;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> path;
while (root || !path.empty()) {
while (root) { path.push(root); root = root->left; }
root = path.top(); path.pop();
if (--k == 0) return root->val;
root = root->right;
}
return -1;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 7 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
3,
1,
4,
null,
2
],
1
]1
[
[
5,
3,
6,
2,
4,
null,
null,
1
],
3
]3
[
[
1
],
1
]1
[
[
2,
1,
3
],
3
]3
[
[
4,
2,
6,
1,
3,
5,
7
],
4
]4
Drafts are saved per language in this browser when storage is available.