解题思路
- 每个节点左右子树差 ≤ 1 → 平衡树
- 任意一个节点左右子树差 > 1 → 非平衡树
代码思路
- 定义一个求二叉树高度的函数depth
- 先处理特殊情况,空树,为平衡树
- root为根节点的左右子树差 ≤ 1 → 继续向下判断子树是否满足条件,直到树中每个节点都判断完成 → 确定为一颗平衡二叉树
- root为根节点的左右子树差 > 1 → 非平衡
代码
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
// 求二叉树的深度
function depth(root){
if(!root)
return 0
// 左树深度
var l=depth(root.left);
// 右树深度
var r=depth(root.right);
return Math.max(l,r)+1;
}
function IsBalanced_Solution(pRoot)
{
// write code here
// 先处理特殊情况,如果是一颗空树,则是平衡二叉树
if(!pRoot)
return true;
// 左右树的差距
let gap=Math.abs(depth(pRoot.left)-depth(pRoot.right));
// 只有当,树中任意一个节点为根节点的左右树高度差小于1,才能确定是平衡树
if(gap<=1)
return IsBalanced_Solution(pRoot.left) && IsBalanced_Solution(pRoot.right);
// 如果左右两树的差距大于1,则可肯定,不是平衡树
else
return false;
}
module.exports = {
IsBalanced_Solution : IsBalanced_Solution
};