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

自顶向下的递归

    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)

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