Leetcode 110. Balanced Binary Tree

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 depth of the two subtrees of every node never differ by more than 1.

题意:判断一棵二叉树是不是高度平衡的。高度平衡的定义是任意非叶子节点的左右子树高度差小于等于1。

思路:
题目的关键是求得每个非叶子节点左右子树的高度,每个非叶子节点的高度等于它左右子树最大的高度值+1.
用分治的方法,从根节点不断向下层求非叶子节点是否是高度平衡,每层节点返回给上层的结果需要包括两个变量(高度、是否平衡),上层通过这两个变量继续判断并把结果层层传递回根节点。

class Result {
    int depth = 0;
    boolean isBalanced = true;
}

public boolean isBalanced(TreeNode root) {
    return helper(root).isBalanced;
}

public Result helper(TreeNode root) {
    Result res = new Result();
    if (root == null) {
        return res;
    }

    Result left = helper(root.left);
    Result right = helper(root.right);
    res.depth = 1 + Math.max(left.depth, right.depth);
    if (!left.isBalanced || !right.isBalanced || Math.abs(left.depth - right.depth) > 1) {
        res.isBalanced = false;
    }

    return res;
}

你可能感兴趣的:(Leetcode 110. Balanced Binary Tree)