题解 | #判断是不是平衡二叉树#【js 实现】

判断是不是平衡二叉树

https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function IsBalanced_Solution(pRoot)
{
    // write code here
    if(pRoot === null) return true
    const left = getTreeDepth(pRoot.left)
    const right = getTreeDepth(pRoot.right)
    if(Math.abs(left - right) > 1) {
        return false
    }
    const leftTree = IsBalanced_Solution(pRoot.left)
    const rightTree = IsBalanced_Solution(pRoot.right)
    return leftTree && rightTree
        
}
function getTreeDepth(root) {
    if(root === null) return 0
    const left = getTreeDepth(root.left)
    const right = getTreeDepth(root.right)
    return Math.max(left, right) + 1
}
module.exports = {
    IsBalanced_Solution : IsBalanced_Solution
};

全部评论

相关推荐

07-02 10:44
门头沟学院 C++
码农索隆:太实诚了,告诉hr,你能实习至少6个月
点赞 评论 收藏
分享
05-05 21:45
已编辑
广州大学 Java
点赞 评论 收藏
分享
_mos_:我以为手抄报简历就已经很顶了,没想到还有表格简历
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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