Kth Smallest Element in a BST
Given the root of a binary search tree and an integer k, return the k-th smallest value (1-indexed) among all node values in the tree.
Open official problem prompt ↗Find the value of rank k in sorted order without materializing the entire sorted list.
Reading a sorted ledger from the top: you count entries one by one and stop the instant you reach line k, never reading the rest.
- Input
- root = [3,1,4,null,2], k = 1
- Output
- 1
- Why
- An inorder walk of the BST yields values in sorted order [1,2,3,4]; the 1st smallest is 1.
The number of nodes is n, with 1 <= k <= n <= 10^40 <= Node.val <= 10^4