「这是我参与11月更文挑战的第 26 天,活动详情查看:2021最后一次更文挑战」
题目来源:110. 平衡二叉树
题目
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 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
题解
提出问题
- 如何求二叉树的高度?
- 什么条件下是平衡二叉树?
分析
-
二叉树的高度的高度与它左右子树的高度相关的
-
当二叉树
root为null时,二叉树的高度是0 -
不为
null时,就需要看左右子树的高度,如果左右子树的高度为0时,二叉树的高度是1
1
- 当左子树的高度为1,右子树为0时,二叉树的高度是2
1
/
3
- 当左子树的高度为1,右子树为1时,二叉树的高度是2
1
/ \
3 2
- 当左子树的高度为2,右子树为1时,二叉树的高度为3
1
/ \
3 2
/
4
-
根据上面描述可以得出一个结论二叉树的高度为左右子树的最大高度+1
Math.max(l,r) + 1 -
那么什么时候平衡呢?根据题目可知左右两个子树的高度差的绝对值不超过 1
Math.abs(l - r) -
首先定义
getHeight方法,通过递归getHeight获取二叉树的高度 -
如何此二叉树为平衡二叉树,最终返回的值为正数,否则为
-1 -
通过递归
getHeight方法求得l左子树高度与r右子树高度 -
当左右子树高度相差的绝对值
>1,否则返回-1就说明不是平衡二叉树
代码实现
/**
* 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) {
return getHeight(root) >= 0
};
var getHeight = function(root){
if(root == null) return 0
let l = getHeight(root.left)
let r = getHeight(root.right)
// 用正负数判断,不平衡返回-1,平衡返回正数
if(l<0 || r<0) return -1
if(Math.abs(l - r) > 1) return -1
return Math.max(l,r) + 1
}