Kth Smallest Element in a BST
Find the k-th smallest value in a binary search tree by visiting its values in sorted order.
Given the root of a binary search tree and a whole number kk = 1k
Example 1
Output: 1
Example 2
Output: 3
The Idea
In a sorted list, finding the third smallest value is easy: you count three from the start. A binary search tree also keeps its values in order, but spread over branches instead of along a line, so the counting is less obvious.
Take Example 2. The input [5, 3, 6, 2, 4, null, null, 1]null
What makes this a binary search tree is a rule about sides. Every value in a node's left part is smaller than the node, and every value in its right part is larger. Under 5, the left part holds 3, 2, 4 and 1, all smaller, and the right part holds 6. The rule holds again at 3, with 2 and 1 on its left and 4 on its right.
So where is the 3rd smallest value? It has no fixed place. The smallest value, 1, sits at the bottom, and the root 5 is only the 5th smallest. The real question is: in what order should the nodes be visited so that the values come out sorted?
The side rule answers it. At any node, its whole left part comes before it in sorted order, and its whole right part comes after it. So visit the left part first, then the node, then the right part, and do the same inside each part. Visiting a tree in this order is called an inorder traversal. Look at the picture below.
The small teal number beside each node is its place in the visit order. The walk first follows the left edge, the path 5, 3, 2, 1 that keeps taking the left child. Node 1 has nothing on its left, so it comes 1st. Then come 2 and 3, because their left parts are done.
The row labelled "values in visit order" reads 1, 2, 3, 4, 5, 6, which is sorted. With k = 3
Solution Approach
Turning the inorder walk into code means settling three things: why not simply list every value first, how to remember the nodes still waiting to be visited, and how to count to k
Listing every value first
Why not collect all the values in sorted order into a list and take the one at position k - 1k = 1
Remembering the way back
On the way down the left edge to 1, the walk passes 5, 3 and 2. Each of them must be visited later, and in reverse order: 2 right after 1, then 3, then 5. The node passed last is needed first.
A stack works exactly like that: a pile where you always take off the item you put on last. In Java, an ArrayDequepushpopreturn
What comes after a node is visited? Its right part. When 3 is popped, its right child 4 is next, and the walk goes down the left edge of that part, pushing as it goes. Node 4 has no left child, so it is pushed and popped at once. When a popped node has no right child, as 1 and 2 do not, the next node is simply the top of the stack.
Counting to k
How does the walk know when to stop? Each pop gives the next value in sorted order, so subtract 1 from k--k == 0k = 1
Java Solution
The method kthSmallest
- First, create an empty stack,
, as anstack , and set a variableArrayDeque to the root.node - An outer loop,
, visits one node per round. Inside it, a second loop walks down the left edge fromwhile (true) , pushing each node ontonode and moving to its left child untilstack isnode .null - Pop the top of
intostack ; it holds the next value in sorted order. Subtract 1 fromnode withk , and if--k is now 0, returnk .node.val - Otherwise set
to its right child. If there is one, the next round walks down that right part's left edge. If it isnode , the next round pushes nothing and pops straight away.null
The outer loop needs no exit test, because k
The mainbuildk
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
public class KthSmallestElementInBST {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public static int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode node = root;
while (true) {
while (node != null) { // go as far left as possible
stack.push(node);
node = node.left;
}
node = stack.pop(); // the next value in sorted order
if (--k == 0) {
return node.val;
}
node = node.right; // values between this one and the next on the stack
}
}
// Builds a tree from the row-by-row form, where null means a missing child.
static TreeNode build(Integer... values) {
if (values.length == 0 || values[0] == null) return null;
TreeNode root = new TreeNode(values[0]);
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int i = 1;
while (i < values.length) {
TreeNode parent = queue.poll();
if (values[i] != null) queue.add(parent.left = new TreeNode(values[i]));
i++;
if (i < values.length && values[i] != null) {
queue.add(parent.right = new TreeNode(values[i]));
}
i++;
}
return root;
}
public static void main(String[] args) {
TreeNode example1 = build(3, 1, 4, null, 2);
System.out.println("Example 1, k = 1: " + kthSmallest(example1, 1));
TreeNode example2 = build(5, 3, 6, 2, 4, null, null, 1);
for (int k = 1; k <= 6; k++) {
System.out.println("Example 2, k = " + k + ": " + kthSmallest(example2, k));
}
System.out.println("[7], k = 1: " + kthSmallest(build(7), 1));
TreeNode chain = build(4, 3, null, 2, null, 1);
System.out.println("[4, 3, null, 2, null, 1], k = 4: " + kthSmallest(chain, 4));
}
}
Running it prints:
Example 1, k = 1: 1
Example 2, k = 1: 1
Example 2, k = 2: 2
Example 2, k = 3: 3
Example 2, k = 4: 4
Example 2, k = 5: 5
Example 2, k = 6: 6
[7], k = 1: 7
[4, 3, null, 2, null, 1], k = 4: 4
The six Example 2 lines give 1, 2, 3, 4, 5 and 6 for kk = 3k = 6
The line for [7]
The counter is easy to get wrong by one. With k-- == 0k = 3k = 6NoSuchElementException
Complexity
The cost depends on the height of the tree, h, which is the number of nodes on its longest path from the root down, and on k
- Time: O(h + k), because every node pushed is either one of the
nodes popped or still on the stack when the method returns, and the stack never holds more than h nodes.k - Space: O(h), because the stack only holds nodes on one path from the root downward, which is about log n nodes in a balanced tree of n nodes and all n in a chain like the last test.
If the tree changes often and the question is asked many times, each node can also store how many nodes its subtree holds. A walk from the root can then skip a whole left part at once and find the k-th value in O(h). The inorder walk with a stack also appears in