复制 //重复遍历了
function IsBalanced_Solution(pRoot) {
if (pRoot == null) return true;
let leftLen = TreeDepth(pRoot.left);
let rightLen = TreeDepth(pRoot.right);
return Math.abs(rightLen - leftLen) <= 1 && IsBalanced_Solution(pRoot.left) && IsBalanced_Solution(pRoot.right);
}
function TreeDepth(pRoot) {
if (pRoot == null) return 0;
let leftLen = TreeDepth(pRoot.left);
let rightLen = TreeDepth(pRoot.right);
return Math.max(leftLen, rightLen) + 1;
}
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
//同时判断
function IsBalanced_Solution(pRoot)
{
// write code here
return TreeDepth(pRoot) !==-1;
}
function TreeDepth(pRoot){
if(pRoot === null) return 0;
var left = TreeDepth(pRoot.left);
if(left === -1)return -1;
var right = TreeDepth(pRoot.right);
if(right === -1)return -1;
return Math.abs(left - right) > 1 ? -1: Math.max(left,right) + 1;
}