-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinary Tree Zigzag Level Order Traversal.cpp
64 lines (62 loc) · 1.68 KB
/
Binary Tree Zigzag Level Order Traversal.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ans;
if(root==NULL)
return ans;
vector<int> vec;
queue<TreeNode*> q;
q.push(root);
q.push(NULL);
//vec.push_back(root->val);
stack<int> stk;
int ct=1;
while(!q.empty())
{
TreeNode* temp=q.front();
q.pop();
if(temp==NULL)
{
if(ct %2==1)
{
ans.push_back(vec);
vec.clear();
}
else
{
for(int i=0;i<vec.size();i++)
stk.push(vec[i]);
vec.clear();
while(!stk.empty())
{
vec.push_back(stk.top());
stk.pop();
}
ans.push_back(vec);
vec.clear();
}
if(!q.empty())
q.push(NULL);
ct+=1;
}else
{
vec.push_back(temp->val);
//stk.push(root->val);
if(temp->left!=NULL)
q.push(temp->left);
if(temp->right!=NULL)
q.push(temp->right);
}
}
return ans;
}
};