Given the root
of a binary search tree, and an integer k
, return the kth
smallest value (1-indexed) of all the values of the nodes in the tree.
Example 1:
Input: root = [3,1,4,null,2], k = 1 Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3 Output: 3
Constraints:
n
.1 <= k <= n <= 104
0 <= Node.val <= 104
class Solution {
int count = 0 ;
int ans = 0 ;
public int kthSmallest(TreeNode root, int k) {
helper(root,k);
return ans ;
}
public void helper(TreeNode root , int k){
if(root == null){
return;
}
helper(root.left , k);
count = count +1 ;
if(count == k){
ans = root.val;
}
helper(root.right,k);
}
}
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India