110. 平衡二叉树

深度优先搜索(前序遍历)

class Solution {
    public boolean isBalanced(TreeNode root) {

        if (root == null){
            return true;
        }

        /**
         * 自顶向下
         * 除了判断左右子树是否是平衡二叉树以外,还要判断左右子树的高度是否小于等于1
         * 对于同一个节点,height()方法会被重复调用,因此导致时间复杂度较高
         */
        return isBalanced(root.left) && isBalanced(root.right) && Math.abs(height(root.left) - height(root.right)) <= 1;
    }

    /**
     * 计算任意节点的高度
     */
    public int height(TreeNode root){

        if (root == null){
            return 0;
        }

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

/**
 * 时间复杂度 O(n^2)
 * 空间复杂度 O(logn)
 */

深度优先搜索(后序遍历)

class Solution {
    public boolean isBalanced(TreeNode root) {

        return height(root) >= 0;
    }

    /**
     * 树的高度自底向上计算更容易,类似于后序遍历
     * 先判断左右孩子是否平衡,如果孩子已经不平衡了,那根节点肯定也不平衡,用-1表示不平衡
     */
    public int height(TreeNode root){

        if (root == null){
            return 0;
        }

        int left = height(root.left);
        int right = height(root.right);

        /**
         * 如果有一个孩子不平衡,或者孩子都平衡,但是高度差大于1,则返回-1
         */
        if (left == -1 || right == -1 || Math.abs(left - right) > 1){
            return -1;
        }

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

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(logn)
 */

https://leetcode-cn.com/problems/balanced-binary-tree/

posted @ 2021-12-25 18:03  振袖秋枫问红叶  阅读(40)  评论(0)    收藏  举报