My C++ BFS solution


  • 0
    Y
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
            vector<vector<int>> result;
            queue<TreeNode*> q;
            q.push(root);
            while(!q.empty()){
                vector<int> level;
                int size = q.size();
                for(int i = 0; i < size; ++i){
                    if(q.front() != nullptr){
                        level.push_back(q.front()->val);
                        q.push(q.front()->left);
                        q.push(q.front()->right);
                    }
                    q.pop();
                }
                if(level.size() > 0) result.insert(result.begin(), level);
            }
            return result;
        }
    

Log in to reply
 

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