判断是不是平衡二叉树

题目描述

输入一棵节点数为 n 二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

思路分析

  • 定义一个求二叉树高度的函数depth
  • 先处理特殊情况,空树,为平衡树
  • root为根节点的左右子树差 ≤ 1 → 继续向下判断子树是否满足条件,直到树中每个节点都判断完成 → 确定为一颗平衡二叉树
  • root为根节点的左右子树差 > 1 → 非平衡

代码参考

function IsBalanced_Solution (pRoot) {
  // write code here
  const depth = (root) => {
    if (!root) return 0
    const left = depth(root.left)
    const right = depth(root.right)
    return Math.max(left, right) + 1
  }
  if (!pRoot) return true
  const gap = Math.abs(depth(pRoot.right) - depth(pRoot.left))
  if (gap <= 1) return IsBalanced_Solution(pRoot.left) && IsBalanced_Solution(pRoot.right)
  else return false
}
posted @ 2023-01-09 23:17  含若飞  阅读(25)  评论(0编辑  收藏  举报