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

判断是不是平衡二叉树

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,
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务