Advertisement
vaibhav1906

Binary Tree Level Order Traversal ii

Jan 4th, 2022
1,018
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<vector<int>> levelOrderBottom(TreeNode* root) {
  4.            if(root==NULL)return {};
  5.         vector<vector<int>> ans;
  6.        
  7.         queue<TreeNode*> q;
  8.         q.push(root);
  9.        
  10.         while(q.size()!=0){
  11.            
  12.             int n = q.size();
  13.            
  14.             vector<int> v;
  15.             for(int i = 0; i<n; i++){
  16.                
  17.                 TreeNode * temp = q.front();
  18.                 q.pop();
  19.                 v.push_back(temp->val);
  20.                 if(temp->left!=NULL){
  21.                     q.push(temp->left);
  22.                 }
  23.                 if(temp->right!=NULL){
  24.                     q.push(temp->right);
  25.                 }
  26.                
  27.             }
  28.            
  29.             ans.push_back(v);
  30.            
  31.         }
  32.         reverse(ans.begin(),ans.end());
  33.         return ans;
  34.     }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement