K-th smallest
Standard · Write code · about 10 min
Given the root of a BST and a number k, return the k-th smallest key in the tree (counting from 1).
Example 1
Input:
[[3,1,4,null,2],1]
Output:
1
In order the keys are 1, 2, 3, 4.
Example 2
Input:
[[5,3,6,2,4,null,null,1],3]
Output:
3
In order: 1, 2, 3, 4, 5, 6. The 3rd is 3.
Constraints
- 1 ≤ k ≤ number of nodes ≤ 1,000
- Keys are distinct integers with -1,000 ≤ key ≤ 1,000
- The tree is a valid BST, given in level order; null marks a missing child
Learn the idea first: Validating a BST and the in-order property, a visual lesson.
More Validating a BST and the in-order property problems
- Find the violating node Standard
- Validate a BST Standard
- Spot the bug: forgotten lower bound Standard
- Recover a swapped BST Challenge