We solved - Kth Smallest Element in a BST. We can calculate total nodes n, and then kth largest elemnt will be (n-k)' th smallest element in BST.
The problem with this approach is that it requires two traversals of the array.
Method 2 - Use Recursive Reverse Inorder Traversal#
By reverse inorder traversal, we mean solving the right child, then node and then left child. We can use recursive solution similar to Kth Smallest Element in a BST.
publicstaticintkthLargest(TreeNode root, int k) {
// count tracks visted node 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) {
// base caseif (root ==null) {
returnnull;
}
// search in the right subtree TreeNode right = kthLargest(root.right, i, k);
// if k'th largest is found in the left subtree, return itif (right !=null) {
return right;
}
// if the current node is k'th largest, return its valueif (i.incrementAndGet() == k) {
return root;
}
// otherwise, search in the left subtreereturn kthLargest(root.left, i, k);
}