-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0103.cpp
More file actions
55 lines (49 loc) · 1.66 KB
/
Copy path0103.cpp
File metadata and controls
55 lines (49 loc) · 1.66 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
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
if (!root) return {};
vector<vector<int>> res;
queue<TreeNode *> q;
bool right = true;
q.push(root);
for (int lvl = 0; !q.empty(); lvl++) {
res.push_back(vector<int>());
for (int t = q.size(); t > 0; t--) {
TreeNode *root = q.front();
q.pop();
res[lvl].push_back(root->val);
if (root->left) q.push(root->left);
if (root->right) q.push(root->right);
}
if (!right) reverse(res[lvl].begin(), res[lvl].end());
right = !right;
}
return res;
}
vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
if (!root) return {};
vector<vector<int>> res;
deque<TreeNode *> d;
bool right = true;
d.push_front(root);
for (int lvl = 0; !d.empty(); lvl++, right = !right) {
res.push_back(vector<int>());
for (int t = d.size(); t > 0; t--) {
TreeNode *root;
if (right) {
root = d.front();
d.pop_front();
if (root->left) d.push_back(root->left);
if (root->right) d.push_back(root->right);
} else {
root = d.back();
d.pop_back();
if (root->right) d.push_front(root->right);
if (root->left) d.push_front(root->left);
}
res[lvl].push_back(root->val);
}
}
return res;
}
};