其他分享
首页 > 其他分享> > BFS框架

BFS框架

作者:互联网

BFS框架

queue<item> myQueue;
while (!queue.empty()){
    sz = queue.size();
    for (int i = 0; i < sz; i++) {
    myQueue.front(), myQueue.pop();
    .......
    if (condition) {
        myQueue.push();
    }
    .......
    }
}

102 二叉树的层序遍历

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if (root == nullptr) {
            return res;
        }
        queue<TreeNode*> queueTree;
        queueTree.push(root);
        while (!queueTree.empty()) {
            vector<int> tempArry;
            int size = queueTree.size();
            for (int i = 0; i < size; i++) {
                TreeNode* node = queueTree.front();
                queueTree.pop();
                tempArry.push_back(node->val);
                if (node->left) {
                    queueTree.push(node->left);
                }
                if (node->right) {
                    queueTree.push(node->right);
                }
            }
            res.push_back(tempArry);
        }
        return res;
    }
};

958 二叉树的完全性检验

class Solution {
public:
    bool isCompleteTree(TreeNode* root) {
        queue<TreeNode*> myQueue;
        myQueue.push(root);
        bool end = false;
        while (!myQueue.empty()) {
            TreeNode* node = myQueue.front();
            myQueue.pop();
            if (node == nullptr) {
                end = true;
            } else {
                if (end) {
                    return false;
                }
                myQueue.push(node->left);
                myQueue.push(node->right);
            }
        }
        return true;
    }
};

标签:node,queue,框架,BFS,queueTree,push,myQueue,root
来源: https://blog.csdn.net/DMC111qwf/article/details/122791636