给定一棵二叉搜索树,请找出其中第k大的节点。

会遍历,知道二叉搜索树特性就能做。

class Solution {
    List<Integer> list=new ArrayList<>();
    public int kthLargest(TreeNode root, int k) {
        rec(root);
        return list.get(list.size()-k);
    }
    public void rec(TreeNode root){
        if(root.left!=null){
            rec(root.left);
        }
        if(root==null){
           return;
        }
        list.add(root.val);
        if(root.right!=null){
            rec(root.right);
        }
    }
}

第一回刷没想着优化,
这里主要记录一下优化。

  1. 遍历到第K大,就应该停止了,把结果拿出来。
  2. 用到了额外的数组空间,能不能不用

注意是第K大,所以顺序右根左;第K小是左根右

class Solution {
    private int res=0,count=0;
    public int kthLargest(TreeNode root, int k) {
        rec(root,k);
        return res;
    }
    public void rec(TreeNode root,int k){
        if(root.right!=null){
            rec(root.right,k);
        }
        if(++count==k){
           
            res= root.val;
           return;
        }
    
         if(root.left!=null){
            rec(root.left,k);
        }
    }
}
发布了45 篇原创文章 · 获赞 110 · 访问量 58万+

猜你喜欢

转载自blog.csdn.net/qq_43390235/article/details/105591246
今日推荐