题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
先说下平衡二叉树概念:任意一子节点的左右子树高度差不大于1 (包含空树)
思路:引入求二叉树深度的方法,遍历左右子树,当左子树-右子树深度的绝对值大于1时,返回-1;否则返回二叉树的深度。
function IsBalanced_Solution(pRoot){
return depth(pRoot)!==-1
}
function depth(pRoot){
if(pRoot == null){
return 0
}
let left=depth(pRoot.left);
if(left === -1){
return -1
}
let right=depth(pRoot.right);
if(right === -1){
return -1
}
return Math.abs(left-right)>1 ? -1 : Math.max(left,right)+1
}