Skip to content
On this page

110. 平衡二叉树

原题链接:LeetCode 110. 平衡二叉树

题目描述

给定一个二叉树,判断它是否是 平衡二叉树

示例 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

难度: Easy


题解代码

javascript
/**
 * 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) {
  if (!root) return true
  return Math.abs(maxHeight(root.left) - maxHeight(root.right)) <= 1 &&
  isBalanced(root.left) &&
  isBalanced(root.right)
};

// 二叉树的最大深度
function maxHeight (root) {
  if (!root) return 0
  return Math.max(maxHeight(root.left), maxHeight(root.right)) + 1
}

技术文档集合