Problem 230 · LeetCode 230(opens in a new tab)
Kth Smallest Element in a BST
MediumBinary search trees
You get root, the top of a binary search tree: for every node, all values in its left subtree are smaller and all values in its right subtree are larger. You also get a number k.
Sort all the values in the tree from smallest to largest and return the one in position k, counting from 1.
Example 1
Input: root = [5, 3, 8, 2, 4, null, 9], k = 2 Output: 3 Why: sorted the values are 2, 3, 4, 5, 8, 9
2 more examples and the constraints
Example 2
Input: root = [7, 3, 9, null, 5], k = 3 Output: 7 Why: sorted they are 3, 5, 7, 9; the third is 7
Example 3
Input: root = [1], k = 1 Output: 1 Why: one node, so it is the smallest
Constraints
- 1 ≤ k ≤ number of nodes ≤ 10,000
- 0 ≤ each node value ≤ 10,000
- The tree is a valid binary search tree
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- In-order listO(n)
- In-order with a stack, stop at kO(h + k)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 nodes and a small k | Verdict |
|---|---|---|---|
| In-order list | O(n) | Simple; always reads the whole tree | |
| In-order with a stack, stop at k | O(h + k) | Best; stops as soon as it has k values |
n = number of nodes, h = height of the tree, k = the position asked for.
Edge cases to test
- k = 1. The answer is the leftmost node; the stack version returns after one slide down.
- k = n. The answer is the largest value, the rightmost node; every node is read.
- One node. [1] with k = 1 returns the root.
- A long chain. A tree that is a straight line is 10,000 levels deep. The recursive walk goes that many calls deep; the stack version does not recurse.
Common mistakes
- Counting k from 0, so the answer is off by one.
- Walking pre-order or level-order, which does not give sorted order.
- Forgetting to move to the right child after a pop, so the loop pops the same path forever.
How to talk through it
- 1Clarify. Is k counted from 1? Is the tree a valid search tree? Can values repeat?
- 2Use the search-tree rule. In-order visits the values in sorted order. Collecting them all is O(n) and easy.
- 3Stop early. Walk in order with a stack and return on the kth pop: O(h + k).
- 4Answer the follow-up. For many queries on a changing tree, keep subtree sizes in each node and steer left or right in O(h).
- 5Test out loud. Run k = 1, k = n and a one-node tree before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?