/*
* function TreeNode(x) {
* this.val = x;
* this.left = null;
* this.right = null;
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return bool布尔型
*/
function IsBalanced_Core(pRoot) {
if (!pRoot) {
// 返回值的类型[是否是平衡;该节点下的高度]
return [true, 0];
}
let h = 1; //如果不是空,那么至少高度为1
let [leftB, leftH] = IsBalanced_Core(pRoot.left);
let [rightB, rightH] = IsBalanced_Core(pRoot.right);
h += leftH > rightH ? leftH : rightH;
// 左子树、右子树不平衡 或者是 左右子树高度差大于1 return false
if (!leftB || !rightB || Math.abs(leftH - rightH) > 1) {
console.log(pRoot.val)
return [false, h];
}
return [true, h];
}
function IsBalanced_Solution(pRoot) {
// write code here
let [res, h] = IsBalanced_Core(pRoot)
return res
}
module.exports = {
IsBalanced_Solution: IsBalanced_Solution,
};