I'm doing some self-studying right now and came across a really mysterious piece of code that "finds the Kth largest node in a BST"
4
/ \
2 8
/ \
5 10
K = 2, Output = 8
Here's the code:
public TreeNode findKthLargest(TreeNode root, int k) {
if(root == null) return null;
int rightSize=0;
if(root.right != null) {
rightSize=size(root.right);
}
if(rightSize+1 == k) {
return root;
} else if(k <= rightSize) {
return findKthLargest(root.right, k);
} else {
return findKthLargest(root.left, k-rightSize-1);
}
}
Can anyone give me a hint or point me in the right direction on HOW this code works? It looks utterly mysterious to me.
Why are we paying so much attention to the "right" side of the BST? Why do we completely ignore the left side?
What is the point of using "rightSize+1 == k" as our check to return our answer?
Note:
Upon second inspection, the "size" function is really weird. I'm practicing on Firecode.io right now and this is their provided structures:
class TreeNode {
int data;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int data) {
this.data = data;
}
TreeNode(int data, TreeNode left, TreeNode right) {
this.data = data;
this.left = left;
this.right = right;
}
}
public int size(TreeNode root);
The 'size' function at the end is not elaborated upon so I'm unsure if this is just some...error on Firecode's part...