Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

二叉树的完全性检验 #304

Open
Sunny-117 opened this issue Nov 8, 2022 · 1 comment
Open

二叉树的完全性检验 #304

Sunny-117 opened this issue Nov 8, 2022 · 1 comment

Comments

@Sunny-117
Copy link
Owner

No description provided.

@lxy-Jason
Copy link
Contributor

/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isCompleteTree = function(root) {
    const queue = [root];
    let leaf = false; //标记是否已经遇到过左右叶子不完整的节点
    while(queue.length){
        let len = queue.length;
        let node = queue.shift();
        if(!node.left && node.right){ //有右节点没左节点,肯定不是完全二叉树
            return false;
        }
        if(leaf && (node.left || node.right)){ // 如果已经遇到过左右节点不完整的节点了,还碰到不是叶子节点的节点,也不是完全二叉树
            return false;
        }
        node.left && queue.push(node.left);
        node.right && queue.push(node.right);
        if(!leaf && (!node.left || !node.right)){ //首次碰到左右不全的节点,leaf为true;
            leaf = true;
        }
    }
    return true;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants