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

判断是不是平衡二叉树

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

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param pRoot TreeNode类
 * @return bool布尔型
 */
function dept(pRoot) {
    if (pRoot === null) return 0;
    let leftDep = dept(pRoot.left);
    if (leftDep == -1) return -1;
    let rightDep = dept(pRoot.right);
    if (rightDep == -1) return -1;
    if (Math.abs(leftDep - rightDep) > 1) return -1;
    return 1 + Math.max(leftDep, rightDep);
}

function IsBalanced_Solution(pRoot) {
    // write code here
    return dept(pRoot) != -1;
}
module.exports = {
    IsBalanced_Solution: IsBalanced_Solution,
};

全部评论

相关推荐

点赞 评论 收藏
分享
牛客38347925...:9,2学生暑期实习失利开始投小厂,给这群人整自信了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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