110. Balanced Binary Tree

题干简述:

判断一个二叉树是否高度平衡。

高度平衡:该树左右子树高度差不超过1

解题思路

为了判断高度是否平衡,必然需要得到左右子树高度差,为此,也需要我们得到左右子树的高度。

高度的求解方法可以通过递归实现统计。

需要注意的是,在递归统计某一 node 高度时,我们需要取的是其左右子树中最高的高度;在比较高度之前,我们可以通过比较当前 node 左右子树高度差是否超过1,来提前得到结果。

题解

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isBalanced = function(root) {
    let res = true;
    if (!root) {
        return res;
    }
    
    function MaxDepth (node) {
        if (!node) {
            return 0
        }
        const leftDepth = MaxDepth(node.left);
        const rightDepth = MaxDepth(node.right);
        if (Math.abs(leftDepth - rightDepth) > 1) {
            res = false;
        }
        return Math.max(leftDepth, rightDepth) + 1;
    }
    
    MaxDepth(root);
    return res;
};

Q.E.D.


Take it easy