Find the K-th Smallest Element in a BST
Trees & GraphsAuto-graded · 18 test casesLast updated
Find the k-th smallest key in a binary search tree represented as a level-order array.
Given the level-order array representation of a Binary Search Tree (BST) and an integer k, return the key of the $k$-th smallest node in the tree (1-indexed).
A valid Binary Search Tree satisfies the standard ordering property: for any given node, all elements in its left subtree are strictly smaller than its key, and all elements in its right subtree are strictly larger than its key.
The input tree root is formatted as a level-order array of values where None indicates missing/null nodes (similar to standard binary tree array representations):
root[0]corresponds to the root node.- Subsequent non-null nodes in broad level-order assign the next elements of the list to their left and right children.
Constraints
- $1 \le N \le 10^4$, where $N$ is the number of nodes in the BST.
- $1 \le k \le N$.
- Tree node keys are distinct integers in the range $[-10^9, 10^9]$.
rootrepresents a valid BST.
Examples
Example 1
Input: kth_smallest_in_bst([5, 3, 6, 2, 4, None, None, 1], 3)
Output: 3
Example 2
Input: kth_smallest_in_bst([3, 1, 4, None, 2], 1)
Output: 1
Example 3
Input: kth_smallest_in_bst([5, 3, 6, 2, 4, None, None, 1], 6)
Output: 6
Hints
Hint 1
Recall that an in-order traversal (left child, root node, right child) of a Binary Search Tree visits elements in strictly ascending order.
Hint 2
You do not need to construct the full sorted sequence of all $N$ elements; you can terminate your traversal early as soon as you visit the $k$-th node.
Hint 3
Using an explicit stack allows you to perform an iterative in-order traversal efficiently without relying on deep recursion.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The key property of a Binary Search Tree (BST) is that performing an in-order traversal (visiting left subtree, current node, then right subtree) processes the tree nodes in strictly ascending sorted order. Thus, the $k$-th node visited during an in-order traversal is guaranteed to be the $k$-th smallest element in the tree.
The algorithm consists of two stages:
- Tree Reconstruction: We parse the input level-order array representation into tree nodes. Each node is represented as a 3-element list
[value, left_child, right_child]. Using a queue (BFS), parent nodes assign their left and right child pointers according to the non-null elements inroot. - Iterative In-order Traversal: Instead of traversing the entire tree or constructing an array of all sorted values, we use an explicit call stack to perform an iterative in-order traversal. We descend along left pointers, pushing nodes onto the stack until reaching a
None. Then we pop from the stack, decrementing $k$. As soon as $k$ reaches zero, the popped node holds our target value and we return immediately.
Complexity Analysis
- Time Complexity:
- Tree Reconstruction: $\mathcal{O}(N)$ where $N$ is the total number of nodes in the BST, as we process each entry in
rootonce. - Traversal: $\mathcal{O}(H + k)$ time where $H$ is the height of the tree, since we push and pop at most $k$ nodes.
- Overall Time Complexity: $\mathcal{O}(N)$ to read the input array and build the tree structures. (If given directly as pointer-linked nodes in memory, time would be $\mathcal{O}(H + k)$).
- Tree Reconstruction: $\mathcal{O}(N)$ where $N$ is the total number of nodes in the BST, as we process each entry in
- Space Complexity: $\mathcal{O}(N)$ space to store the constructed node objects and queue/stack buffers.
Python Reference Solution
from collections import deque
from typing import List, Optional
def kth_smallest_in_bst(root: List[Optional[int]], k: int) -> int:
if not root or root[0] is None:
raise ValueError("tree must be non-empty")
# Step 1: Reconstruct the tree from level-order array representation
nodes = [None] * len(root)
nodes[0] = [root[0], None, None] # Node structure: [val, left, right]
queue = deque([0])
value_index = 1
while queue and value_index < len(root):
parent_index = queue.popleft()
parent = nodes[parent_index]
# Left child assignment
if value_index < len(root) and root[value_index] is not None:
nodes[value_index] = [root[value_index], None, None]
parent[1] = nodes[value_index]
queue.append(value_index)
value_index += 1
# Right child assignment
if value_index < len(root) and root[value_index] is not None:
nodes[value_index] = [root[value_index], None, None]
parent[2] = nodes[value_index]
queue.append(value_index)
value_index += 1
# Step 2: Perform iterative in-order traversal stopping at the k-th node
stack = []
current = nodes[0]
remaining = k
while stack or current is not None:
while current is not None:
stack.append(current)
current = current[1] # Move to left child
current = stack.pop()
remaining -= 1
if remaining == 0:
return current[0]
current = current[2] # Move to right child
raise ValueError("k is out of range")