-
Notifications
You must be signed in to change notification settings - Fork 77
/
solution.cpp
51 lines (50 loc) · 1.03 KB
/
solution.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
/**
* Definition for binary tree
* 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> >result;
if (!root)
return result;
vector<int>vec;
queue<TreeNode*>q1;
TreeNode *temp = root;
enum Dir{L,R};
Dir dir = L;
q1.push(root);
while (!q1.empty())
{
queue<TreeNode *>q2;
while (!q1.empty())
{
temp = q1.front();
q1.pop();
if (temp->left)
q2.push(temp->left);
if (temp->right)
q2.push(temp->right);
vec.push_back(temp->val);
}
if (dir == R)
{
reverse(vec.begin(), vec.end());
dir = L;
}
else
dir = R;
result.push_back(vec);
vec.clear();
q1 = q2;
}
return result;
}
};