当前位置:网站首页>Judge whether a tree is a complete binary tree

Judge whether a tree is a complete binary tree

2022-06-21 06:09:00 Move forward_ On my way

problem :

There is a binary tree , Given its root node root, Please design an algorithm to judge whether it is a complete binary tree

analysis :

Because it is necessary to judge whether a tree is a complete binary tree , Consider using BFS Algorithm , Judge layer by layer :

1、 If a node has a right subtree but no left subtree , Just go back to false

2、 If a node has no subtree , The next node is not a leaf node , return false

Code :

bool check(TreeNode* root){
    bool leaf = false;
    queue<TreeNode*> q;
    q.push(root);
    while(!q.empty()){
        int sz = q.size();
        for(int i=0; i<sz; ++i){
            TreeNode* curr = q.front(); q.pop();
            TreeNode* l = curr->left;
            TreeNode* r = curr->right;
            if(r && !l || leaf&&l || leaf&&r) return false;
            if(l) q.push(l);
            if(r) q.push(r);
            else leaf = true;
        }
    }
    return true;
}

原网站

版权声明
本文为[Move forward_ On my way]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206210556467996.html