Kth Smallest Element in a BST solution explained
To find the kth smallest value in a binary search tree, walk the tree in order (left subtree, node, right subtree), which visits values from smallest to largest, and stop at the kth node you visit. With an explicit stack this takes O(h + k) time and O(h) extra space, where h is the height of the tree.
By Evin JohnPublished 8 min read
The problem, in plain terms
You get a binary search tree: every value in a node's left subtree is smaller than the node, and every value in its right subtree is larger. You also get a whole number k, at least 1 and no more than the number of nodes. Return the value that would sit in position k if you wrote all the tree's values out in increasing order.
20
/ \
12 31
/ \ /
5 15 27
\
17
sorted order: 5, 12, 15, 17, 20, 27, 31
k = 3 -> 15
k = 5 -> 20Before coding, ask whether values are unique (usually yes for this problem; if not, ask whether duplicates count separately), whether k is always valid, and whether the tree is balanced. The last question tells you how deep a recursive solution might go.
How the problem is used in interviews
It checks two things at once: whether you know the defining property of a binary search tree well enough to use it, and whether you can write a tree traversal without recursion. A candidate who collects every value and sorts it has missed the point, so interviewers often let you start there and then ask what the tree already gives you for free. Expect a follow-up about frequent updates, which turns the question into a small data structure design.
A slower starting idea
Visit every node in any order, gather the values in a list, sort the list, and return the item at index k minus one. It is correct for any binary tree, which is exactly its weakness: it ignores the ordering the BST already has. Cost is O(n log n) time and O(n) space, and it always looks at every node even when k is 1.
def kth_smallest_brute(root, k):
values = []
def collect(node):
if node:
values.append(node.val)
collect(node.left)
collect(node.right)
collect(root)
return sorted(values)[k - 1]The optimal approach: in-order traversal that stops early
Pattern: in-order traversal of a BST. An in-order walk goes left, visits the node, then goes right. In a binary search tree that order is ascending, so the kth node visited holds the answer. To stop the moment you reach it, and to avoid one stack frame per level on a tall tree, simulate the recursion with your own stack: push nodes while walking left, pop one when you cannot go further left, count it, then move into its right subtree.
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def kth_smallest(root, k):
stack, node = [], root
while stack or node:
while node: # go as far left as possible
stack.append(node)
node = node.left
node = stack.pop() # next value in sorted order
k -= 1
if k == 0:
return node.val
node = node.right # then walk the right subtree
raise ValueError("k is larger than the number of nodes")function kthSmallest(root, k) {
const stack = [];
let node = root;
while (stack.length > 0 || node !== null) {
while (node !== null) { // go as far left as possible
stack.push(node);
node = node.left;
}
node = stack.pop(); // next value in sorted order
k -= 1;
if (k === 0) return node.val;
node = node.right; // then walk the right subtree
}
throw new Error("k is larger than the number of nodes");
}Trace it on the example with k equal to 3. The walk pushes 20, 12 and 5, pops 5 (count 1), has no right child, pops 12 (count 2), moves to 15, pushes it, pops 15 (count 3) and returns. Nodes 17, 20, 27 and 31 are never touched.
Follow-up: the tree changes and k keeps changing
If you insert and delete often and ask for different k each time, a fresh walk costs O(h + k) per query. Store in every node the size of its subtree, keep it updated on insert and delete, and you can descend directly: if k is at most the size of the left subtree, go left; if it is exactly one more, the current node is the answer; otherwise subtract the left size plus one and go right. Each query is then O(h), which is O(log n) on a balanced tree.
class SizedNode:
def __init__(self, val):
self.val, self.left, self.right, self.size = val, None, None, 1
def size(n):
return n.size if n else 0
def insert(root, val):
if root is None:
return SizedNode(val)
if val < root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
root.size += 1
return root
def kth_with_sizes(root, k):
node = root
while node:
left = size(node.left)
if k <= left:
node = node.left
elif k == left + 1:
return node.val
else:
k -= left + 1
node = node.right
raise ValueError("k out of range")The insert here is plain and recursive to keep it short; a production version would also rebalance (a red-black or AVL tree, or a treap) so h stays logarithmic, and would update sizes on delete as well.
Complexity summary
| Approach | Time per query | Extra space |
|---|---|---|
| Collect all values and sort | O(n log n) | O(n) |
| Full in-order walk into a list | O(n) | O(n) |
| Iterative in-order, stop at k | O(h + k) | O(h) |
| Subtree sizes stored in nodes | O(h) | O(1) beyond the stored sizes |
On a balanced tree h is about log n; on a tree built from sorted input with no rebalancing, h can be n. That is why the stack version matters: a recursive walk on a chain of a hundred thousand nodes will exceed Python's default recursion limit, while the explicit stack handles it.
Edge cases to try
- A single node with k equal to 1.
- k equal to the number of nodes, which returns the maximum.
- A tree that leans entirely left or entirely right.
- Negative values and zero.
- k larger than the tree, if the interviewer says it can happen: decide whether to raise an error or return a sentinel.
Pitfalls
- Using pre-order or level order and expecting sorted output.
- Counting k from zero in one place and from one in another.
- Recursing on both subtrees after the answer is found, which wastes the early exit.
- Forgetting to move to the right child after popping, which loops forever or skips values.
- Claiming O(log n) time without saying the tree must be balanced.
How to explain it out loud
Fictional example
- Candidate
- Because this is a search tree, an in-order walk gives me the values already sorted. So the kth node I visit in order is the answer, and I can stop there.
- Candidate
- I'll do the walk with a stack instead of recursion: dive left pushing nodes, pop one, count it, then step into its right child. That is O(h + k) time and O(h) space.
- Candidate
- If this ran many times on a tree that keeps changing, I'd store subtree sizes in each node so a query becomes a single path from the root.
Related problems
Rebuilding a tree from its traversal orders is the reverse of this exercise: see Construct Binary Tree from Preorder and Inorder. Another way to pull out the kth value, this time from numbers arriving one by one, is the heap in Kth Largest Element in a Stream. For a post-order tree walk that carries a value back up, try Binary Tree Maximum Path Sum.
Practicing with Natively
Tree questions are easier to reason about with a drawing in front of you. During practice, Natively can read a tree problem from a screenshot on Mac or Windows, suggest the traversal that fits, and point out the recursion-depth question before you hit it. It also transcribes your mock session, so you can check later whether you stated the BST property before relying on it. More on the AI interview assistant.
Questions people ask
How do you find the kth smallest element in a BST?
Walk the tree in order (left, node, right), which visits a binary search tree's values in ascending order, and return the value of the kth node visited. An explicit stack lets you stop as soon as you reach it.
What is the time complexity of kth smallest in a BST?
O(h + k) time and O(h) extra space for the iterative in-order walk, where h is the tree height. On a balanced tree h is about log n; on a skewed tree it can be n.
Why use an iterative traversal instead of recursion?
It makes stopping early simple and avoids one call frame per level, so a very tall, unbalanced tree cannot overflow the call stack.
How do you answer many kth smallest queries on a changing tree?
Store each node's subtree size and keep it updated on insert and delete. Then compare k with the left subtree's size at each step and descend, which takes O(h) per query.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
