Example 1
- Input
- root = [5,3,6,2,4,null,null,1], k = 3
- Output
- 3
Inorder gives [1,2,3,4,5,6]. Counting from one, the visits are 1, then 2, then 3, so rank three returns 3. The root value is not its rank.
Given the root of a binary search tree and an integer k, return the kth smallest value using the fact that an inorder walk visits values in ascending order. Every k between 1 and the tree size is valid.
Given the root of a binary search tree and an integer k, return the kth smallest value in the tree, counting from 1.
A binary search tree keeps smaller values on the left and larger values on the right, so an inorder walk of left, node, then right visits values in strictly increasing order.
1 <= k <= n <= 10^4, where n is the number of nodes0 <= Node.val <= 10^4Inorder gives [1,2,3,4,5,6]. Counting from one, the visits are 1, then 2, then 3, so rank three returns 3. The root value is not its rank.
Inorder gives [1,2,3,4], so rank one returns 1. Its right child 2 comes after 1; early stopping returns before entering that right subtree.
A single node is both the smallest and largest value. Rank one returns 0; zero is a valid answer, not a missing-node marker.
This right-only chain has inorder [1,2,3,4]. Since k equals the node count, early stopping must visit every node before returning 4.
A rank is a position in sorted order, not a distance from the root. In a binary search tree, every left-subtree value is smaller than its root and every right-subtree value is larger. Visiting left subtree, node, then right subtree therefore produces sorted values without sorting. In Example 1, this order is [1,2,3,4,5,6]; the third visit is 3, although the root is 5. A stack remembers ancestors waiting for their left subtrees to finish. We can either collect all values or count visits and stop at the requested rank.
Reveal Full Inorder Collect: intuition, complexity, and code
0 and k = 1 returns 0; test nodes for null rather than testing their values.k = 1, return the leftmost value. A 10,000-node left chain still requires 10,000 pushes before the first pop.k = n, the answer is the rightmost value and every node is visited, so early stopping saves no visits.3 does in Example 1. Return before traversing that larger subtree.order[k] instead of order[k - 1] confuses one-based ranks with zero-based indices.5 first.A BST turns inorder traversal into a sorted stream. An explicit stack preserves the next visit without copying or modifying the tree, and a rank query can stop after k visits. This shortcut relies on the BST property; arbitrary binary trees do not have sorted inorder values.