15% off all plans & roadmaps Use code
See plansKth Smallest Element in a BST
- LeetCode 230
- Medium
- Tree Traversal Patterns (DFS & BFS)
- Recursive Inorder Traversal
Updated
TL;DR: Find the kth smallest value in a binary search tree. An inorder traversal visits values in ascending order, so you count visited nodes and stop at the kth.
Problem
You are given the root of a binary search tree and an integer k. Return the kth smallest value, counting from 1, among the values of all nodes in the tree.
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
- The tree has
nnodes. 1 <= k <= n <= 10^40 <= Node.val <= 10^4
Constraints that matter
- n is at most 10^4, so even O(n log n) with a sort is fast enough. The real goal is to show you can use the BST ordering instead of ignoring it.
- 1 <= k <= n means the answer always exists. You never need to handle a k larger than the node count.
- A skewed tree can have height 10^4. Recursion in Python can hit its default depth limit of 1000, so raise the limit or use an explicit stack.
- Node values are between 0 and 10^4, so there is no overflow risk and no need to treat negative values specially.
- The input is a valid BST, so left subtree values are smaller and right subtree values are larger. That property is what lets you skip sorting.
Hints
Hint 1
This is a recursive inorder traversal problem.
Hint 2
Treat the tree as an unordered bag of numbers.
Solution
Intuition
This is a recursive inorder traversal problem. The phrase to notice is "binary search tree plus a rank question". A BST keeps smaller values on the left and larger values on the right at every node.
It is like unpacking a sorted shelf one item at a time. The stack is the set of shelf sections you have not finished, and the counter is how many items you have taken out.
Inorder traversal visits the left subtree, then the node, then the right subtree. Because of the BST rule, every value in the left subtree comes before the node, and every value in the right subtree comes after it. Applied at every node, this produces the values in ascending order.
So the kth node you visit during an inorder traversal is the kth smallest value. You do not need to store or sort anything. Keep a counter, decrement it at each visit, and return the value when it hits zero.
The counter also gives you an early exit. Once you have the answer, the rest of the tree is irrelevant. That cuts the work from visiting all n nodes to visiting about H + k nodes, where H is the tree height.
Worked example
Input: root = [3,1,4,null,2], k = 1 Output: 1 Explanation: The tree has root 3, a left child 1 whose right child is 2, and a right child 4. Sorted, the values read 1, 2, 3, 4. The 1st smallest is 1.
Approach 1: Brute force: collect everything, then sort
Treat the tree as an unordered bag of numbers. Visit every node in any order, copy each value into a list, sort the list, and read position k - 1.
This ignores the BST property completely. It works on any binary tree, which is why it is the baseline. The traversal below uses an explicit stack so a 10^4 deep tree cannot overflow the call stack.
Steps
- Create an empty list
valuesand a stack holding the root. - Pop a node, append its value to
values, and push its non-null children. - Repeat until the stack is empty, so every node has been copied.
- Sort
valuesin ascending order. - Return
values[k - 1], since k is 1-indexed.
Dry run
Tree: root 3, left 1 (with right child 2), right 4. Stack starts as [3].
- Pop 3, values = [3]. Push 1 and 4.
- Pop 4 (pushed last), values = [3, 4]. No children.
- Pop 1, values = [3, 4, 1]. Push its right child 2.
- Pop 2, values = [3, 4, 1, 2]. Stack is empty.
- Sort: [1, 2, 3, 4]. With k = 1, return index 0, which is
1.
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(n) |
Here n is the number of nodes. The traversal pops each node once, which is O(n) work. Sorting n values costs O(n log n) and dominates. The list holds all n values, and the stack never holds more than n entries, so space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
values = []
stack = [root]
while stack:
node = stack.pop()
if node:
values.append(node.val)
stack.append(node.left)
stack.append(node.right)
values.sort()
return values[k - 1]JavaTested in our runner
import java.util.*;
class Solution {
public int kthSmallest(TreeNode root, int k) {
List<Integer> values = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
values.add(node.val);
if (node.left != null) stack.push(node.left);
if (node.right != null) stack.push(node.right);
}
Collections.sort(values);
return values.get(k - 1);
}
}C++Tested in our runner
#include <vector>
#include <stack>
#include <algorithm>
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
std::vector<int> values;
std::stack<TreeNode*> st;
st.push(root);
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
values.push_back(node->val);
if (node->left) st.push(node->left);
if (node->right) st.push(node->right);
}
std::sort(values.begin(), values.end());
return values[k - 1];
}
};JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthSmallest = function(root, k) {
const values = [];
const stack = [root];
while (stack.length > 0) {
const node = stack.pop();
values.push(node.val);
if (node.left) stack.push(node.left);
if (node.right) stack.push(node.right);
}
values.sort((a, b) => a - b);
return values[k - 1];
};GoTested in our runner
import "sort"
func kthSmallest(root *TreeNode, k int) int {
values := []int{}
stack := []*TreeNode{root}
for len(stack) > 0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
values = append(values, node.Val)
if node.Left != nil {
stack = append(stack, node.Left)
}
if node.Right != nil {
stack = append(stack, node.Right)
}
}
sort.Ints(values)
return values[k-1]
}C#Tested in our runner
public class Solution {
public int kthSmallest(TreeNode root, int k) {
var values = new List<int>();
var stack = new Stack<TreeNode>();
stack.Push(root);
while (stack.Count > 0) {
TreeNode node = stack.Pop();
values.Add(node.val);
if (node.left != null) stack.Push(node.left);
if (node.right != null) stack.Push(node.right);
}
values.Sort();
return values[k - 1];
}
}
Solution pattern
Recursive Inorder Traversal
Approach 2: Recursive inorder into a sorted listRecursive Inorder Traversal
What's slow: the sort. You pay O(n log n) to put values in order, but the BST already stores them in order. You only have to read them in the right sequence.
The insight that fixes it: a recursive inorder traversal (left, node, right) emits values in ascending order by itself. Append each value as you visit it, and the list comes out sorted with no sort call. Then index it at k - 1.
This is linear time, but it still builds the full list of n values even when k is 1. Recursion depth equals the tree height, so Python needs a raised recursion limit for a skewed tree.
Steps
- Create an empty list
values. - Define
inorder(node): return if the node is null. - Call
inorderon the left child. - Append the node's value to
values. - Call
inorderon the right child. - Run
inorder(root)and returnvalues[k - 1].
Dry run
Tree: root 3, left 1 (right child 2), right 4.
inorder(3)callsinorder(1). Node 1 has no left child, so it appends 1. values = [1].- Node 1 then visits its right child 2. Node 2 appends 2. values = [1, 2].
- Back at 3, append 3. values = [1, 2, 3].
- Visit 3's right child 4 and append it. values = [1, 2, 3, 4].
- With k = 1, return
values[0], which is1.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Here n is the node count. Each node is entered once and does constant work, so time is O(n). The list stores n values, and the recursion stack reaches at most height H, which is at most n. Total extra space is O(n).
PythonTested in our runner
import sys
from typing import List, Optional
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
# A skewed tree can be 10^4 deep, above Python's default limit.
sys.setrecursionlimit(max(sys.getrecursionlimit(), 20000))
values = []
def inorder(node):
if not node:
return
inorder(node.left)
values.append(node.val)
inorder(node.right)
inorder(root)
return values[k - 1]JavaTested in our runner
import java.util.*;
class Solution {
private List<Integer> values;
public int kthSmallest(TreeNode root, int k) {
values = new ArrayList<>();
inorder(root);
return values.get(k - 1);
}
private void inorder(TreeNode node) {
if (node == null) return;
inorder(node.left);
values.add(node.val);
inorder(node.right);
}
}C++Tested in our runner
#include <vector>
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
std::vector<int> values;
inorder(root, values);
return values[k - 1];
}
private:
void inorder(TreeNode* node, std::vector<int>& values) {
if (!node) return;
inorder(node->left, values);
values.push_back(node->val);
inorder(node->right, values);
}
};JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthSmallest = function(root, k) {
const values = [];
const inorder = (node) => {
if (!node) return;
inorder(node.left);
values.push(node.val);
inorder(node.right);
};
inorder(root);
return values[k - 1];
};GoTested in our runner
func kthSmallest(root *TreeNode, k int) int {
values := []int{}
var inorder func(node *TreeNode)
inorder = func(node *TreeNode) {
if node == nil {
return
}
inorder(node.Left)
values = append(values, node.Val)
inorder(node.Right)
}
inorder(root)
return values[k-1]
}C#Tested in our runner
public class Solution {
private List<int> values;
public int kthSmallest(TreeNode root, int k) {
values = new List<int>();
Inorder(root);
return values[k - 1];
}
private void Inorder(TreeNode node) {
if (node == null) return;
Inorder(node.left);
values.Add(node.val);
Inorder(node.right);
}
}Approach 3: Inorder traversal with early stopOptimal
What's slow: the previous approach visits all n nodes and stores all n values, even when you only need the first k. For k = 1 in a balanced tree, that is thousands of wasted visits and a huge list.
The insight that fixes it: you need a counter, not a list. Walk the tree in inorder, subtract one from k at each visited node, and return the moment k reaches 0. Nothing after that node matters.
The code below unrolls the recursion into an explicit stack. The stack holds the path of ancestors whose left subtrees you are still exploring, which is exactly what the call stack would hold. This avoids recursion depth limits on skewed trees. A recursive version does the same work with a shared counter.
Steps
- Create an empty stack and set
curto the root. - While
curis not null, push it and move to its left child. This reaches the smallest unvisited node. - Pop the top of the stack. This is the next value in sorted order.
- Decrement k. If k is 0, return the popped node's value.
- Set
curto the popped node's right child and repeat from the second step. - Loop while
curis non-null or the stack is non-empty.
Dry run
Tree: root 3, left 1 (right child 2), right 4. k = 1.
| Step | Action | Stack (bottom to top) | cur | k |
|---|---|---|---|---|
| 0 | start | [] | 3 | 1 |
| 1 | push 3, go left | [3] | 1 | 1 |
| 2 | push 1, go left | [3, 1] | null | 1 |
| 3 | pop 1, k becomes 0, return 1 | [3] | 0 |
The answer is 1, found after visiting only 2 nodes. With k = 3 on the same tree, you would pop 1 (k = 2), go right and push 2, pop 2 (k = 1), pop 3 (k = 0) and return 3.
Complexity
| Time | O(H + k) |
|---|---|
| Space | O(H) |
Here H is the tree height. Every node is pushed once and popped at most once, and the loop stops after the kth pop. Pushes equal pops plus the final stack size, so there are at most k + H pushes and the time is O(H + k). That is O(n) when k = n.
The stack holds one root-to-node path, so it never exceeds H entries. Space is O(log n) for a balanced tree and O(n) for a skewed one.
PythonTested in our runner
from typing import List, Optional
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
stack = []
cur = root
while cur or stack:
# Go as far left as possible to find the next smallest node.
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
k -= 1
if k == 0:
return cur.val
cur = cur.right
return -1JavaTested in our runner
import java.util.*;
class Solution {
public int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
k--;
if (k == 0) return cur.val;
cur = cur.right;
}
return -1;
}
}C++Tested in our runner
#include <stack>
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
std::stack<TreeNode*> st;
TreeNode* cur = root;
while (cur || !st.empty()) {
while (cur) {
st.push(cur);
cur = cur->left;
}
cur = st.top();
st.pop();
k--;
if (k == 0) return cur->val;
cur = cur->right;
}
return -1;
}
};JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthSmallest = function(root, k) {
const stack = [];
let cur = root;
while (cur || stack.length > 0) {
while (cur) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
k--;
if (k === 0) return cur.val;
cur = cur.right;
}
return -1;
};GoTested in our runner
func kthSmallest(root *TreeNode, k int) int {
stack := []*TreeNode{}
cur := root
for cur != nil || len(stack) > 0 {
for cur != nil {
stack = append(stack, cur)
cur = cur.Left
}
cur = stack[len(stack)-1]
stack = stack[:len(stack)-1]
k--
if k == 0 {
return cur.Val
}
cur = cur.Right
}
return -1
}C#Tested in our runner
public class Solution {
public int kthSmallest(TreeNode root, int k) {
var stack = new Stack<TreeNode>();
TreeNode cur = root;
while (cur != null || stack.Count > 0) {
while (cur != null) {
stack.Push(cur);
cur = cur.left;
}
cur = stack.Pop();
k--;
if (k == 0) return cur.val;
cur = cur.right;
}
return -1;
}
}Common mistakes
- Using preorder or postorder instead of inorder. Only left, node, right visits a BST in sorted order. Visit the node between the two recursive calls.
- Decrementing the counter before recursing left, such as
k -= 1at the top of the function. The node counts only after its whole left subtree is done. Put the decrement after the left call. - Forgetting an early exit in the recursive version. Without a check like
if self.result is not None: return, the traversal keeps walking after the answer is found. The result stays correct but you lose the O(H + k) bound. - Using
-1or0as the "not found" sentinel and testing it carelessly. Node values start at 0, so0is a valid answer. Use-1,Noneor a separate found flag, and check it consistently. - Using
values[k]instead ofvalues[k - 1]. The problem is 1-indexed and arrays are 0-indexed, so the kth smallest sits at index k - 1. - Passing k by value in a recursive helper (in C++ or Go). Each call then decrements its own copy and the count is lost. Use a reference or pointer, or a member or closure variable.
Edge cases
- Single node, k = 1: the answer is the root value, and the stack loop returns on the first pop.
- k = n: you must visit every node and return the maximum value, which is the rightmost node.
- Left-skewed tree of 10^4 nodes: the stack or recursion reaches depth 10^4. Python recursion needs a raised limit, and the explicit stack handles it as is.
- Right-skewed tree (a sorted linked list going right): the stack stays at depth 1 or 2 in the iterative version, and k = n still returns the last node.
- Root value 0 with k = 1: the answer is 0, so do not treat 0 as "no answer".
- Duplicate values (if the tree allows them): inorder still counts each node separately, so the kth node visited is returned.
Follow-ups interviewers ask
- The BST is modified often and you query the kth smallest often. How do you optimize?
- Store a subtree size in every node. At a node, let L be the size of its left subtree. If k <= L, go left. If k == L + 1, return this node. Otherwise go right with k - L - 1. A query then costs O(H). Insert and delete update the sizes along the path they touch, which is also O(H). With a self-balancing tree, H is O(log n), so both operations are O(log n).
- The tree never changes but you answer many queries. What do you do?
- Run one inorder traversal and keep the sorted array. Each query is then an O(1) index lookup at k - 1. You pay O(n) once for time and space, and that cost is spread over all queries.
- How would you find the kth largest instead, or handle a tree that is not a BST?
- For the kth largest in a BST, traverse in reverse inorder (right, node, left) and count the same way. For a general binary tree, the ordering trick is gone. Keep a max-heap of size k while traversing, which costs O(n log k) time and O(k) extra space, or collect and sort.
Kth Smallest Element in a BST FAQ
What is the time complexity of Kth Smallest Element in a BST?
The inorder traversal with early stop runs in O(H + k), where H is the tree height. It descends H levels to the leftmost node and then visits k nodes. In the worst case, k = n or a skewed tree, this is O(n). The sort-based brute force is O(n log n).
Why use inorder traversal for Kth Smallest Element in a BST?
A BST puts smaller values in the left subtree and larger values in the right subtree at every node. Inorder visits left, node, right, so it emits values in ascending order. The kth visited node is therefore the kth smallest, and you need no sorting.
Can Kth Smallest Element in a BST be solved in O(1) extra space?
Yes, with Morris traversal. It temporarily links each node's inorder predecessor back to the node so you can climb up without a stack, then removes the links. Time stays O(n) in the worst case, and it modifies the tree while running, so you must finish the traversal to restore it. The stack and recursive versions use O(H) space instead.
Does the recursive solution work in Python for LeetCode 230?
It works if you raise the recursion limit. The tree can have 10^4 nodes in a chain, and Python's default limit is about 1000 frames. Either call sys.setrecursionlimit with a larger value or use the explicit-stack version, which has no depth issue.
How do you solve Kth Smallest Element in a BST in Java or Python?
Use the same algorithm in both. Push nodes down the left spine onto a stack, pop one, decrement k, return its value when k hits 0, then move to its right child. The page above has tested code for Python, Java, C++, JavaScript, Go and C#.
How is this different from Validate BST?
Both rely on inorder order. Here you count nodes until you reach position k. In Validate BST you check that each visited value is greater than the previous one. The traversal is the same, only the work done at each visit changes.
Asked at
See which companies ask this — Pro
Related problems
- Validate Binary Search Tree · same technique: Recursive Inorder Traversal
- Delete Node in a BST · same technique: Recursive Inorder Traversal
- Binary Search Tree Iterator · same technique: Recursive Inorder Traversal
- Binary Tree Inorder Traversal · same technique: Recursive Inorder Traversal
- Minimum Absolute Difference in BST · same technique: Recursive Inorder Traversal
- Binary Tree Maximum Path Sum · next harder, same pattern
- Binary Tree Level Order Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)
- Binary Tree Right Side View · same pattern: Tree Traversal Patterns (DFS & BFS)
- Construct Binary Tree from Preorder and Inorder Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)
- Lowest Common Ancestor of a Binary Search Tree · same pattern: Tree Traversal Patterns (DFS & BFS)