I have the following correct Java code to find the in-order kth element in a binary tree.
private static int count = 0;
public static <T> T findkthInOrder(Node<T> root, int k) {
count=0;
return findkthInOrder(root, k, 0);
}
public static <T> T findkthInOrder(Node<T> root, int k,int a) {
if (root == null)
return null;
T rt = findkthInOrder(root.left, k, 0);
if (rt != null)
return rt;
count++;
if (count == k) {
return root.data;
}
return findkthInOrder(root.right, k, 0);
}
But I really want to remove the use of count, possibly by making use of an additional method argument. I also want to keep it as recursion, and require the method findkthInOrder to return T type value.
Can anyone please help me with this? Thank you.
This is overkill but here goes…The only mutable number class I could find in Java was
java.util.concurrent.atomic.AtomicIntegerI had made premature optimization, fixed now.
Here is alternate solution: