-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBTzigzagOrderTraversal103.cpp
More file actions
106 lines (100 loc) · 2.64 KB
/
Copy pathBTzigzagOrderTraversal103.cpp
File metadata and controls
106 lines (100 loc) · 2.64 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/**
* 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) {
queue<TreeNode*>nodes;
queue<int>level;
//cout << level.front() << endl;
vector<vector<int>>answer;
vector<int>ans;
TreeNode* anode;
int count = 1, prev = 0;
if (!root)return answer;
nodes.push(root);
level.push(count);
while(!nodes.empty()) {
anode = nodes.front();
nodes.pop();
count = level.front();
level.pop();
//handle node value
ans.push_back(anode->val);
//cout << count << " , " << level.front() << endl;
if (level.empty() || level.front()!=count ) {
answer.push_back(ans);
ans.clear();
}
count++;
if (anode->left) {
nodes.push(anode->left);
level.push(count);
}
if (anode->right) {
nodes.push(anode->right);
level.push(count);
}
}
for (int i = 1; i < answer.size(); i+=2) {
reverse(answer[i].begin(),answer[i].end());
}
return answer;
}
};
//the fatest method
/**
* 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) {
queue<TreeNode*> que;
vector<vector<int>> res;
// check empty
if(!root) return res;
que.push(root);
int level = 0;
while(!que.empty()){
int size = que.size();
vector<int> temp(size, 0);
int index;
if(level%2==0){
index = 0;
} else {
index = size-1;
}
for(int i=0;i<size;i++){
TreeNode* cur = que.front();
que.pop();
temp[index] = cur->val;
if(level%2==0){
index++;
} else {
index--;
}
if(cur->left){
que.push(cur->left);
}
if(cur->right){
que.push(cur->right);
}
}
res.push_back(temp);
level++;
}
return res;
}
};