Very simple C++ using 2 queues alternatively, without using any depth/marker variables


  • 0
    E
    class Solution {
    public:
        vector<int> levelNums(queue<TreeNode*>& q1, queue<TreeNode*>& q2) {
            vector<int> level;
            while ( !q1.empty() ) {
                if( q1.front() != NULL ) {
                    level.push_back( q1.front()->val );
                    q2.push(q1.front()->left);
                    q2.push(q1.front()->right);
                }
                q1.pop();
            }
            return level;
        }
        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> levels;
    
            queue<TreeNode*> q1, q2;
            q1.push(root);
            vector<int> level;
            while( !q1.empty() || !q2.empty() ) {
                if( !q1.empty() )
                    level = levelNums(q1, q2);
                else
                    level = levelNums(q2, q1);
                if(level.size() != 0)
                    levels.push_back( level );
            }
            
            return levels;
        }
    };
    

Log in to reply
 

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