My 15ms C++ BFS solution


  • 0
    D
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int> > r;
        vector<int> level;
        queue<TreeNode*> q;
        queue<TreeNode*> l;
        if( !root ) return r;
        q.push(root);
        while( !q.empty() ) {
            root = q.front();
            q.pop();
            level.push_back(root->val);
            
            if( root->left ) 
                l.push(root->left);
                
            if( root->right )
                l.push(root->right);
            
            if( q.empty() ) {
                r.push_back(level);
                level.resize(0);
                //copy(l.begin(), l.end(), q.begin());
                while( !l.empty() ) {
                    q.push(l.front());
                    l.pop();
                }
            }
                
        }
        reverse(r.begin(),r.end());
        return r;
    }
    

    It's very simple. I think we can optimize it by without copying the second queue elements. But I didn't find a way till now


Log in to reply
 

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