Advertisement
Guest User

LevelxLevel Alternate

a guest
Jan 23rd, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<vector<int>> zigzagLevelOrder(TreeNode* root)
  4.     {
  5.         vector<vector<int>> zigzag;
  6.         vector<int> temporal;
  7.         bool valor = true, cambio = true;
  8.         if(root==NULL)
  9.         {
  10.             return zigzag;
  11.         }
  12.         int posicion = 0;
  13.         stack<TreeNode*> s;
  14.         queue<TreeNode*> q;
  15.         q.push(root);
  16.         while(!q.empty()||!s.empty())
  17.         {
  18.             if(valor)
  19.             {
  20.                 temporal.push_back(q.front()->val);
  21.                 if(q.front()->left!=NULL)
  22.                 {
  23.                     s.push(q.front()->left);
  24.                 }
  25.                 if(q.front()->right!=NULL)
  26.                 {
  27.                     s.push(q.front()->right);
  28.                 }
  29.                 q.pop();
  30.                 if(q.empty())
  31.                 {
  32.                     valor = false;
  33.                 }
  34.                
  35.             }
  36.             else
  37.             {
  38.                 temporal.push_back(s.top()->val);
  39.                 if(s.top()->left!=NULL)
  40.                 {
  41.                     q.push(s.top()->left);
  42.                 }
  43.                 if(s.top()->right!=NULL)
  44.                 {
  45.                     q.push(s.top()->right);
  46.                 }
  47.                 s.pop();
  48.                 if(s.empty())
  49.                 {
  50.                     valor = true;
  51.                 }
  52.             }
  53.             if(cambio!=valor)
  54.             {
  55.                 cambio = !cambio;
  56.                 zigzag.push_back(temporal);
  57.                 temporal.clear();
  58.                 posicion++;
  59.             }
  60.         }
  61.         return zigzag;
  62.     }
  63. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement