nikunjsoni

103

Mar 31st, 2021
88
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13. public:
  14.     vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
  15.         if(!root) return {};
  16.         queue<TreeNode*> q;
  17.         vector< vector<int> > res;
  18.         q.push(root);
  19.         int level = 0;
  20.        
  21.         while(!q.empty()){
  22.             int sz = q.size();
  23.             vector<int> curr(sz);
  24.             for(int i=0; i<sz; i++){
  25.                 TreeNode *front = q.front();
  26.                 q.pop();
  27.                 if(level) curr[sz-i-1] = front->val;
  28.                 else curr[i] = front->val;
  29.                 if(front->left) q.push(front->left);
  30.                 if(front->right) q.push(front->right);
  31.             }
  32.             res.push_back(curr);
  33.             level = !level;
  34.         }
  35.         return res;
  36.     }
  37. };
RAW Paste Data