LeetCode热题(JS版) - 110. 平衡二叉树

58 阅读1分钟

题目

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

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

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

示例 1:

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

示例 2:

输入:root = [1,2,2,3,3,null,null,4,4]
输出:false

示例 3:

输入:root = []
输出:true

提示:

树中的节点数在范围 [0, 5000] 内
-104 <= Node.val <= 104

思路:每棵子树都平衡

  • 求高度的函数
  • 递归判断平衡
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function isBalanced(root: TreeNode | null): boolean {
    if(!root) return true;
    
    const height = (node) => {
        if(!node) return 0;
        return Math.max(height(node.left), height(node.right)) + 1;
    }

    return Math.abs(height(root.left) - height(root.right)) <=1 
        && isBalanced(root.left)
        && isBalanced(root.right)
};

image.png

思路2:只要有一颗子树不平衡就不平衡

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function isBalanced(root: TreeNode | null): boolean {
    // 有一个不平衡
    const height = (node) => {
        if(!node) return 0;
        const hl = height(node.left);
        const hr = height(node.right);

        if(hl < 0 || hr < 0 || Math.abs(hl - hr) > 1) return -1;

        return Math.max(hl, hr) + 1;
    }
    return height(root) >=0
};

image.png