33. Kth Smallest and Largest element in BST
Given the root node of a binary search tree (BST) and an integer k.
Return the kth smallest and largest value (1-indexed) of all values of the nodes in the tree.
Return the 1st integer as kth smallest and 2nd integer as kth largest in the returned array.
Example 1:
Input : root = [3,1,4,null,2] , k = 1
Output : [1, 4]
Explanation :
The 1st smallest value in given BST is 1.
The 1st largest value in given BST is 4.
Example 2:
Input : root = [5, 3, 6, 2, null, null, null, 1] , k = 3
Output : [3, 3]
Explanation :
The 3rd smallest value in given BST is 3.
The 3rd largest value in given BST is 3.
Now Your Turn!
Pick the correct output for the given inputInput : root = [3,1,4,null,2] , k = 2
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- The number of nodes in the tree is n.
- 1 <= k <= n <= 104
- 0 <= Node.val <= 105