先求出每一个结点的高度->getHeight(root)
递归地判断是否为平衡二叉树->isBalanced(root)
function IsBalanced_Solution(pRoot)
{
function getHeight(root){
if(root == null) return 0;
root.height = Math.max(getHeight(root.left), getHeight(root.right)) + 1;
return root.height;
}
function isBalanced(root){
if(root == null)
return true;
if(root.left==null && root.right==null)
return true;
if(root.left==null)
return root.right.height<=1 && isBalanced(root.right);
if(root.right==null)
return root.left.height<=1 && isBalanced(root.left);
return Math.abs( root.left.height - root.right.height ) <=1 && isBalanced(root.left) && isBalanced(root.right);
}
getHeight(pRoot);
return isBalanced(pRoot);
}
module.exports = {
IsBalanced_Solution : IsBalanced_Solution
};