knakul853

Untitled

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