Kth smallest element in a BST
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Uber's technical phone screen, last asked Feb 2026. It tests trees, binary search tree and traversal.
Given the root of a binary search tree and an integer k, return the k-th smallest value in the tree, counting from 1. In a binary search tree every value in a node's left subtree is smaller than the node's value and every value in its right subtree is larger.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
kth_smallest(root: TreeNode, k: int) -> int—TreeNodehasval,leftandright.1 <= k <=the number of nodes.
Example
The tree is written in level order, with None for a missing child:
root = [5, 3, 6, 2, 4, None, None, 1]
5
/ \
3 6
/ \
2 4
/
1
kth_smallest(root, 3) -> 3 # in order: 1, 2, 3, 4, 5, 6
kth_smallest([10], 1) -> 10
Constraints
-
1 <= number of nodes <= 10^4; values are distinct integers in[-10^5, 10^5].
Clarifying questions
- Is
kalways valid? - Are the values distinct?
- How tall can the tree be? A degenerate tree makes recursion depth an issue.
- Will this be called many times on a tree that changes?
What a strong answer covers
- An in-order traversal visits values in ascending order; count nodes and stop at the
k-th. - An iterative version with an explicit stack, O(h + k) time and O(h) space, which stops early instead of collecting every value.
- Why collecting the full sorted list is O(n) and wasteful when
kis small. - Tests:
k = 1,kequal to the size, a tree that is a single chain.
Follow-ups
- The tree is modified often and
kth_smallestis called often. Store subtree sizes in each node to answer in O(h). - Return the
k-th largest instead. - Do it in O(1) extra space (Morris traversal).
Where it's asked
- Uber · Technical phone screen · Last asked Feb 202660 min · One medium problem with a follow-up, or two short ones; sometimes object-oriented design
What it tests
trees · binary search tree · traversal
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
