-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsolution103.cpp
More file actions
78 lines (70 loc) · 1.35 KB
/
solution103.cpp
File metadata and controls
78 lines (70 loc) · 1.35 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* Binary Tree Zigzag Level Order Traversal
*
* Nov 8th, 2016
*/
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
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) {
queue<TreeNode *> q;
vector<vector<int> > ret;
if (root == NULL) return ret;
q.push(root);
int i = 0;
while (!q.empty())
{
queue<TreeNode *> tmpQueue;
vector<int> tmpVec;
while (!q.empty())
{
TreeNode *node = q.front();
q.pop();
if (node -> left)
{
tmpQueue.push(node -> left);
}
if (node -> right)
{
tmpQueue.push(node -> right);
}
tmpVec.push_back(node -> val);
}
q = tmpQueue;
if (i % 2 != 0)
{
reverse(tmpVec.begin(), tmpVec.end());
}
i ++;
ret.push_back(tmpVec);
}
return ret;
}
};
int main(int argc, char **argv)
{
Solution s;
TreeNode *root = new TreeNode(3);
root -> left = new TreeNode(9);
root -> right = new TreeNode(20);
root -> right -> left = new TreeNode(15);
root -> right -> right = new TreeNode(7);
vector<vector<int> > ret = s.zigzagLevelOrder(root);
for (auto i : ret)
{
for (auto j : i)
{
cout << j << " ";
}
cout << endl;
}
}