Loading...
Loading...
Given the root of a Binary Search Tree (BST) and an integer k, return the kth smallest element (1-indexed) among all node values in the tree.
Recall that a BST has the property that for every node, all values in its left subtree are smaller, and all values in its right subtree are larger.
Input:
root — the root of a BST represented as a level-order (BFS) array where null indicates a missing node.k — an integer indicating which smallest element to find (1-indexed).Output:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
Explanation: The in-order traversal of this BST is [1, 2, 3, 4]. The 1st smallest element is 1.
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3
Explanation: The in-order traversal is [1, 2, 3, 4, 5, 6]. The 3rd smallest element is 3.
Input: root = [2,1,3], k = 2
2
/ \
1 3
Output: 2
Explanation: The in-order traversal is [1, 2, 3]. The 2nd smallest element is 2.
k.1 <= number of nodes <= 10^4 0 <= Node.val <= 10^4 1 <= k <= number of nodes All Node.val are unique Input tree is guaranteed to be a valid BST