Retrieve Kth Smallest Element from Array-Encoded BST
Trees & GraphsAuto-graded · 19 test casesLast updated
Tests in-order traversal of a binary search tree encoded in parallel arrays, with early termination and iterative stack management.
Problem
You are given a binary search tree where all node values are distinct integers. Your task is to find the kth smallest element in this tree, where k uses one-based indexing.
The tree structure is encoded using parallel arrays:
values[i]holds the integer value stored at node ileft[i]contains the index of node i's left child, or -1 if none existsright[i]contains the index of node i's right child, or -1 if none existsrootis the index of the root node, or -1 if the tree is empty
All arrays have the same length n, which equals the total number of nodes.
Return the kth smallest value in the tree. If the tree is empty or k falls outside the valid range [1, n], return -1 as a sentinel value.
Note that -1 may also appear as a legitimate node value. The caller distinguishes error cases from valid results by checking whether k was in range.
Constraints
- 0 ≤ n ≤ 200,000, where n = len(values) = len(left) = len(right)
- Each child index is either a valid node index or -1
- The arrays encode a single acyclic tree structure reachable from root
- All values are distinct integers (may include negative numbers)
- The tree satisfies the binary search tree property: for every node, all values in its left subtree are smaller and all values in its right subtree are larger
- k is an integer and may be outside the valid range
- The tree may be highly unbalanced (a single chain of depth n)
Examples
Example 1
Input: find_kth_smallest_bst([3, 1, 4, 2], [1, -1, -1, -1], [2, 3, -1, -1], 0, 1)
Output: 1
Example 2
Input: find_kth_smallest_bst([3, 1, 4, 2], [1, -1, -1, -1], [2, 3, -1, -1], 0, 3)
Output: 3
Example 3
Input: find_kth_smallest_bst([], [], [], -1, 1)
Output: -1
Hints
Hint 1
In-order traversal of a BST visits nodes in ascending order by value
Hint 2
You can stop traversing as soon as you've visited k nodes—no need to see the entire tree
Hint 3
Use an explicit stack to avoid recursion depth issues with deep trees
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is that an in-order traversal of a binary search tree yields values in strictly ascending order. By performing in-order traversal (left subtree → current node → right subtree), we visit nodes from smallest to largest. The kth node we visit contains the kth smallest value.
Rather than collecting all values and sorting, we traverse only as far as needed. We maintain a counter and return immediately upon reaching the kth visit.
Since the tree can be extremely deep (up to 200,000 nodes in a single chain), recursion would exceed Python's default stack limit. Instead, we use an iterative approach with an explicit stack to simulate the traversal.
The algorithm works as follows:
- Validate input: if the tree is empty or k is outside [1, n], return -1 immediately
- Initialize an empty stack and start at the root
- For each position, descend as far left as possible, pushing each node onto the stack
- Pop the top node from the stack—this is the next smallest unvisited value
- Increment the visit counter; if it equals k, return this node's value
- Move to the popped node's right child and repeat (its right subtree contains the next values in order)
Correctness
The stack maintains nodes whose left subtrees have been processed but which haven't been visited yet. Every node on the stack is larger than all previously visited nodes.
- When we push all nodes along a left spine, the top of the stack becomes the leftmost (minimum) node in that subtree
- Popping a node constitutes visiting it; its remaining successors in sorted order are its right subtree followed by the ancestors still on the stack
- By moving to the right child after each pop, we ensure right subtrees are fully explored before returning to ancestors
This guarantees nodes are visited in strictly ascending order. Since 1 ≤ k ≤ n and all n nodes are reachable from the root, we always reach the kth visit for valid input.
Complexity
Time: O(h + k) where h is tree height. We initially descend at most h nodes along the leftmost path. Each subsequent visit may push additional nodes along left spines of right subtrees. Every pushed node is eventually popped exactly once. Total work is bounded by the initial descent plus k visits plus the spines leading to them, giving O(h + k). Worst case is O(n) when k = n.
Space: O(h) for the explicit stack. The stack contains at most one root-to-node path at any time. For a balanced tree this is O(log n); for a chain it's O(n). Crucially, this is heap-allocated memory, avoiding recursion depth failures.
Full Solution
from typing import List
def find_kth_smallest_bst(values: List[int], left: List[int], right: List[int], root: int, k: int) -> int:
n = len(values)
if root == -1 or k < 1 or k > n:
return -1
stack = []
node = root
visited = 0
while stack or node != -1:
while node != -1:
stack.append(node)
node = left[node]
node = stack.pop()
visited += 1
if visited == k:
return values[node]
node = right[node]
return -1