Kth Smallest Element in a BST
Medium
Topics
Given the root of a binary search tree and an integer k, return the k-th smallest value (1-indexed).
Example 1
the 1th smallest
An in-order walk of a BST emits values in sorted order, so the 1th node it reaches is the answer — 1. The walk can stop there rather than finishing the tree, which is the whole saving over collecting and indexing.
Tree given in level-order (breadth-first);
null marks a missing child.Input: root = [3,1,4,null,2], k = 1 Output: 1
Example 2
smaller valuesthe 3th smallest
Input: root = [5,3,6,2,4,null,null,1], k = 3 Output: 3
Constraints
- 1 <= k <= number of nodes <= 10^4
- 0 <= Node.val <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
An in-order traversal of a BST yields values in sorted order. So the k-th value produced by an in-order walk is the answer — you can even stop early once you have counted k.
Approach
- Do an in-order traversal (left, node, right).
- Count nodes as you visit them.
- When the count reaches k, that node’s value is the answer.
Dry Run
tree 5 3 6 2 4 null null 1 and k = 3
5
/ \
3 6
/ \
2 4
/
1
An inorder walk of a BST emits values in sorted order, so the kth pop is the
answer. The stack holds the un-visited ancestors:
push the left spine stack [5, 3, 2, 1]
pop 1 k becomes 2 right child is null
push the left spine stack [5, 3, 2]
pop 2 k becomes 1 right child is null
push the left spine stack [5, 3]
pop 3 k becomes 0 answer
answer 3
Nothing below or right of the 3 is ever touched. That is the advantage over
collecting the whole inorder list: the walk stops the moment the count runs out,
so k=1 costs only the depth of the leftmost spine.
Two conditions are doing real work. `while st or node` has to test both: use
`while node` and the loop ends as soon as the leftmost spine is exhausted, with
everything still on the stack unvisited -- k=3 then returns -1, though k=1 happens
to still work because it finishes before the spine runs out.
And k is decremented on pop then compared to 0. Compare to 1 instead and you get
the (k-1)-th element: k=3 returns 2, and k=1 never matches at all, falling off the
end at -1. Decrementing before the pop rather than after changes nothing, since
nothing between the two reads k.Complexity
- Time — O(h + k): descend to the smallest, then pop k nodes.
- Space — O(h): the explicit stack.
Common Pitfalls
- The loop condition is
while st or node. Usingwhile nodeends the moment the leftmost spine is exhausted, so everything still waiting on the stack is never visited and the answer comes back wrong or missing. kis decremented on pop and compared to 0 after. Comparing to 1 instead returns the (k-1)-th element, and for k=1 it never matches at all -- k reaches 0 on the first pop and the loop runs off the end returning -1.- Decrementing
kbefore the pop rather than after is not a bug here, which is worth knowing before you go looking for one: both orders pass every case, because nothing between them readsk.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def kthSmallest(self, root, k):
st=[]; node=root
while st or node:
while node:
st.append(node); node=node.left
node=st.pop(); k-=1
if k==0: return node.val
node=node.right
return -1import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> st=new ArrayDeque<>();
TreeNode node=root;
while(!st.isEmpty()||node!=null) {
while(node!=null) {
st.push(node);
node=node.left;
}
node=st.pop();
if(--k==0)return node.val;
node=node.right;
}
return -1;
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> st;
TreeNode* node=root;
while(!st.empty()||node) {
while(node) {
st.push(node);
node=node->left;
}
node=st.top();
st.pop();
if(--k==0)return node->val;
node=node->right;
}
return -1;
}
};/** Tree node shape: { val, left, right } */ /**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/ var kthSmallest = function(root, k) {
const st=[];
let node=root;
while(st.length||node) {
while(node) {
st.push(node);
node=node.left;
}
node=st.pop();
k--;
if(k===0)return node.val;
node=node.right;
}
return -1;
};