knakul853

Untitled

Jul 22nd, 2020
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  1. /**
  2. knakul853
  3.  */
  4. class Solution {
  5. public:
  6.     vector<vector<int>> levelOrder(TreeNode* root) {
  7.        
  8.         queue<TreeNode*> q;
  9.         q.push(root);
  10.         vector<vector<int>>ans;
  11.        
  12.         if( !root ) return ans;
  13.        
  14.         while( !q.empty() )
  15.         {
  16.             vector<int>res;
  17.             int sz = (int)q.size();
  18.             queue<TreeNode*>temp;
  19.            
  20.             for( int i=0; i<sz; i++ )
  21.             {
  22.                 auto node = q.front();q.pop();
  23.                   res.push_back(node->val);
  24.                
  25.                 if( node->left ) temp.push( node->left );
  26.                 if( node->right ) temp.push( node->right );
  27.             }
  28.            
  29.           q = temp;
  30.             ans.push_back( res );
  31.            
  32.         }
  33.        
  34.         return ans;
  35.        
  36.     }
  37. };
Add Comment
Please, Sign In to add comment