题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
```/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function IsBalanced_Solution(pRoot)
{
// write code here
//题目特别提示空树是平衡二叉树
//递归思想,对每一棵子树进行高度遍历,高度差不超过1,如果有一层超过则返回false
//考察基础算法:求二叉树深度,递归(后序遍历)
if(pRoot === null) {return true}
if(Math.abs(depth(pRoot.left)-depth(pRoot.right))>1) {return false} //判断左右子树的深度差值
return IsBalanced_Solution(pRoot.left) && IsBalanced_Solution(pRoot.right) //递归判断左右子树是否为平衡二叉树
}
function depth(node){
if(node === null) {return 0}
let left = depth(node.left)
let right = depth(node.right)
return Math.max(left,right)+1
}
module.exports = {
IsBalanced_Solution : IsBalanced_Solution
};