首页 > 学院 > 开发设计 > 正文

二叉搜索树的第k个节点

2019-11-08 00:58:31
字体:
来源:转载
供稿:网友

给定一颗二叉搜索树,请找出其中的第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) ;     }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表