您的位置:首页 > 其它

二叉搜索树的第k个节点

2017-02-21 19:44 274 查看
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
递归搜索
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;

}

}
*/
public class Solution {
private int num = 0 ;
TreeNode KthNode(TreeNode pRoot, int k){
if(k == 0)return null ;
if(pRoot == null)return null ;
TreeNode re = KthNode(pRoot.left , k) ;
if(re != null)return re ;
num++ ;
if(num == k)return pRoot ;
return KthNode(pRoot.right , k) ;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: