C++ 9ms BFS solution


  • 0
     vector<vector<int>> levelOrderBottom(TreeNode* root) {
            vector<vector<int>>res;
            if(!root) return res;
            vector<int>v;
            deque<TreeNode*>q;
            deque<TreeNode*>next_level;
            q.push_back(root);
            while(!q.empty()){
                TreeNode* node=q.front();
                q.pop_front();
                v.push_back(node->val);
                if(node->left) next_level.push_back(node->left);
                if(node->right) next_level.push_back(node->right);
                if(q.empty()) res.push_back(v),q=next_level,next_level.clear(),v.clear();
            }
            reverse(res.begin(),res.end());
            return res;
        }
    

Log in to reply
 

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