C++ Solution | Simple & Easy to understand | 8 ms | 12.5MB
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>>ans;
if(root==nullptr){
return ans;
}
queue<TreeNode*>q;
q.push(root);
q.push(nullptr);
vector<int>temp;
while(!q.empty()){
TreeNode*f=q.front();
if(f==nullptr){
ans.push_back(temp);
q.pop();
if(!q.empty()){
q.push(nullptr);
}
temp.clear();
}
else{
temp.push_back(f->val);
q.pop();
if(f->left){
q.push(f->left);
}
if(f->right){
q.push(f->right);
}
}
}
reverse(ans.begin(),ans.end());
return ans;
}
};Please like the post if the solution helps you.
Thank you & Happy Coding!!!