public class E54KthBSTNode {
private static int index;
public static BinaryTreeNode getKthNode(BinaryTreeNode root, int k){
if (root == null)
return null;
index = k;
return getKthNodeCore(root);
}
private static BinaryTreeNode getKthNodeCore(BinaryTreeNode root) {
BinaryTreeNode target = null;
if (root.left != null)
target = getKthNodeCore(root.left);
if (target == null){
if (index == 1)
target = root;
index--;
}
if (target == null && root.right != null)
target = getKthNodeCore(root.right);
return target;
}
}