C++ BFS Solution using two queus


  • 0
    Y
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> result;
            if (!root) return result;
    
            queue<TreeNode*> neighbors[2];
            vector<int> vals;
            int cur = 0;
            neighbors[cur].push(root);
            
            while (!neighbors[cur].empty())
            {
                auto node = neighbors[cur].front();
                neighbors[cur].pop();
                
                if (node->left) neighbors[cur^1].push(node->left);
                if (node->right) neighbors[cur^1].push(node->right);
                
                vals.push_back(node->val);
                if (neighbors[cur].empty()) {
                    result.push_back(vals);
                    vals.clear();
                    cur = cur ^ 1;
                }
            }
            return result;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.