Iterative but slow version


  • 0
    C
    class Solution {
    public:
        vector<vector<int>> levelOrderBottom(TreeNode* root)
        {
            if(!root) return vector< vector<int> >();
            
            vector< vector<int> > level_nodes;
            
            queue<TreeNode*> q;
            
            q.push(root);
            
            while( !q.empty() )
            {
                int level_cnt = q.size();
                
                level_nodes.insert(level_nodes.begin(), vector<int>());
                vector< vector<int> > ::iterator level_iter = level_nodes.begin();
                    
                while(level_cnt-- > 0)
                {
                    TreeNode *node = q.front();
                    q.pop();
                    
                    level_iter->push_back(node->val);
                    
                    if(node->left) q.push(node->left);
                    if(node->right) q.push(node->right);
                }
            }
            
            return level_nodes;
        }
    };

Log in to reply
 

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