中序遍历的遍历结果是有序的,只需要每次执行中序时候计数,达到k就返回。
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k) {
count=0;
return mid(pRoot,k);
}
static int count = 0;
public TreeNode mid(TreeNode pRoot,int k){
if(null == pRoot)
return pRoot;
TreeNode res = mid(pRoot.left,k);
if(null != res)
return res;
count++;
//System.out.println(count+":"+pRoot.val);
if(k==count)
return pRoot;
return mid(pRoot.right,k);
}
}