题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
思路
递归中序遍历,每遍历一个结点–k,当k=0时,当前结点即为所求结点。
注意点
- 使用TreeNode[] res和int[] kk的数组引用代入递归函数中,若为TreeNode类型和int 类型则为值传递,不起作用;或者可以使用成员变量。
- 找到所求结点后如何减少后面的递归次数。
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot==null||k<=0){
return null;
}
TreeNode[] res=new TreeNode[1];
int[] kk=new int[1];
kk[0]=k;
doKthNode( pRoot,kk, res);
return res[0];
}
public void doKthNode(TreeNode pRoot, int[] k,TreeNode[] res){
//此处阻止所求结点上层结点继续遍历右子树
if(k[0]<1){
return;
}
if(pRoot.left!=null){
doKthNode( pRoot.left, k, res);
}
k[0]--;
if(k[0]==0){
res[0]=pRoot;
//此处阻止所求结点继续遍历右子树
return;
}
if(pRoot.right!=null){
doKthNode( pRoot.right, k, res);
}
}
}