题解 | #判断是不是平衡二叉树#

判断是不是平衡二叉树

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
};
全部评论

相关推荐

合适才能收到offe...:招聘上写这些态度傲慢的就别继续招呼了,你会发现hr和面试官挺神的,本来求职艰难就可能影响一些心态了,你去这种公司面试的话,整个心态会炸的。
点赞 评论 收藏
分享
03-12 14:52
已编辑
长沙学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务