Difficulty: Easy

Related Topics: Tree, Depth-first Search

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

Example 1:

110. Balanced Binary Tree - 图1

  1. Input: root = [3,9,20,null,null,15,7]
  2. Output: true

Example 2:

110. Balanced Binary Tree - 图2

Input: root = [1,2,2,3,3,null,null,4,4]
Output: false

Example 3:

Input: root = []
Output: true

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -10 <= Node.val <= 10

Solution

Language: Java

class Solution {

    public boolean isBalanced(TreeNode root) {
        boolean[] isBalanced = new boolean[1];
        // 最开始认为它是平衡的
        isBalanced[0] = true;

        dfs(root, isBalanced);

        return isBalanced[0];
    }

    // 定义:平衡二叉树的左右子树高度差不能超过 1
    // 该 dfs 主要是求树的高度,顺便计算左右子树的高度差
    private int dfs(TreeNode root, boolean[] isBalanced) {
        if(root == null) return 0;

        int left_height = dfs(root.left, isBalanced);
        int right_height = dfs(root.right, isBalanced);

        // 标记这棵树不是平衡二叉树
        if (isBalanced[0]) {
            // 平衡条件,左右子树的高度差要小于2
            isBalanced[0] = Math.abs(left_height - right_height) < 2;
        }

        // 计算树的高度
        // 左右子树中去最高的那个,在加上本层的高度
        return Math.max(left_height, right_height) + 1;
    }
}