publicintfindKthSmallest(TreeNode root, int k) {
// counter tracks visited nodes// `AtomicInteger` is used as`Integer` is passed by value in Java// OR use some wrapper class AtomicInteger counter =new AtomicInteger(0);
TreeNode kthNode = helper(root, k, counter);
return kthNode ==null?-1: kthNode.val;
}
public TreeNode helper(TreeNode root,int k,AtomicInteger counter) {
if (root ==null) {
returnnull;
}
TreeNode left = helper(root.left, k, counter);
// if k'th smallest node is foundif (left !=null) {
return left;
}
// if the root is k'th smallest nodeif (counter.incrementAndGet() == k) {
return root;
}
return helper(root.right, k, counter);
}