因为二叉搜索树的中序遍历是有序,因此只要中序遍历到k次就可以了
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
int count=0;
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot==null||k<=0) return null;
TreeNode target=null;
if(pRoot.left!=null) target=KthNode(pRoot.left,k);
count++;
if(target==null&&count==k){//如果遍历到这时,target仍然为空,且count=k那么target赋值为pRoot
target=pRoot;
}
if(target==null&&pRoot.right!=null){//必须要此时target仍然为null,才进行遍历右子树,如果target不为空,那么不用遍历,直接返回即可。
target=KthNode(pRoot.right,k);
}
return target;
}
}