[路飞]_平衡二叉树

202 阅读1分钟

110. 平衡二叉树

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。

示例1

image.png

输入: root = [3,9,20,null,null,15,7]
输出: true

解题思路

自顶向下

从根节点开始枚举二叉树节点左右两个子树的高度,

代码

var isBalanced = function(root) {
    if(root === null) return true;
    let left = helper(root.left);
    let right = helper(root.right);
    return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right)
    function helper(node){
        if(node === null)return 0;
        let left = helper(node.left)
        let right = helper(node.right);
        return Math.max(left,right)+1
    }
};

自下向顶

从底至顶返回子树最大高度,子节点最大高度作为父节点高度的参考依据;可以降低整个计算过程的时间复杂度

代码

var isBalanced = function(root) {
    if(root === null) return true;
    let result = true
    helper(root)
   function helper(node){
       if(node === null) return 0;
       let left = helper(node.left);
       let right = helper(node.right);
       if(Math.abs(left - right) > 1)result = false;
       return Math.max(left,right)+1

   }
   return result
};

或者

var isBalanced = function(root) {
    if(root === null) return true;
   return helper(root) !== -1
   function helper(node){
       if(node === null) return 0;
       let left = helper(node.left);
       let right = helper(node.right);
       if(Math.abs(left - right) > 1 || left === -1 || right === -1) return -1
       return Math.max(left,right)+1
   }
};