题解 | #判断是不是完全二叉树#

判断是不是完全二叉树

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

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param root TreeNode类
 * @return bool布尔型
 */

function isCompleteTree(root) {
    // write code here
    // 考虑使用逐层遍历二叉树,取出每一层的所有节点,放入arr中
    // 如果出现一个节点的子树不全,后续的节点不能有子树

    if (!root) return true;
    let arr = [root];
    let mark = false; //当这个标记变为true后,后面不能再出现子树
    while (arr.length > 0) {
        current = arr.shift();//取出第一个根节点,观察情况
        if (mark && (current.left || current.right)) {
            // 如果前面有不完全的子树,这里还在后续发现了子树,则返回false
            return false;
        }
        if(!current.left&¤t.right){
            // 有右无左返回false
            return false;
        }
        if(current.left){arr.push(current.left)}
        else{ mark =true}
        if(current.right){arr.push(current.right)}
        else{ mark =true}

    }
    return true
}
module.exports = {
    isCompleteTree: isCompleteTree,
};

全部评论

相关推荐

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