首页 > 其他 > 详细

二叉树--平衡二叉树(leetcode 110

时间:2020-07-19 11:32:34      阅读:45      评论:0      收藏:0      [点我收藏+]

自顶向下的递归

    public boolean isBalanced(TreeNode root) {
        if (root == null){
            return true;
        }

        return Math.abs(height(root.left) - height(root.right)) < 2 && isBalanced(root.left) && isBalanced(root.right);
    }

    public int height(TreeNode root){
        if (root == null){
            return 0;
        }

        return Math.max(height(root.left), height(root.right)) + 1;
    }

这个方法计算高度会有大量冗余

时间复杂度:O(nlogn)
空间复杂度:O(n)


自底向上的递归

如果是自底向上的计算,每个子树的高度只会被计算一次

此方法为本题的最优解法,但“从底至顶”的思路不易第一时间想到。

思路是对二叉树做先序遍历,从底至顶返回子树最大高度,若判定某子树不是平衡树则 “剪枝” ,直接向上返回

    public int recur(TreeNode root){
        if (root == null){
            return 0;
        }
        int left = recur(root.left);
        if (left == -1){
            return -1;
        }
        int right = recur(root.right);
        if (right == -1){
            return - 1;
        }

        return Math.abs(right - left) < 2 ? Math.max(left, right) + 1 : -1;
    }
    
    public boolean isBalanced(TreeNode root){
        return recur(root) != -1;
    }

时间复杂度:O(n)
空间复杂度:O(n)

二叉树--平衡二叉树(leetcode 110

原文:https://www.cnblogs.com/swifthao/p/13338203.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!