zentan66 / daily-coding

日常手写算法,编程题
0 stars 0 forks source link

LeetCode-平衡二叉树 #12

Open zentan66 opened 3 years ago

zentan66 commented 3 years ago

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

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

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

zentan66 commented 3 years ago

编码

var isBalanced = function (root) {
  function height(root) {
    if (!root) {
      return 0
    }
    let leftHeight = height(root.left)
    let rightHeight = height(root.right)
    if (
      leftHeight === -1 ||
      rightHeight === -1 ||
      Math.abs(leftHeight - rightHeight) > 1
    ) {
      return -1
    }
    return Math.max(leftHeight, rightHeight) + 1
  }
  return height(root) >= 0
}