-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy path103.zigzagLevelOrder.cpp
More file actions
47 lines (42 loc) · 1.13 KB
/
103.zigzagLevelOrder.cpp
File metadata and controls
47 lines (42 loc) · 1.13 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
/**
* 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;
queue<TreeNode*> q;
queue<int> level;
q.push(root);
level.push(0);
int cur = -1;
while(!q.empty()) {
TreeNode* node = q.front();
int l = level.front();
q.pop();
level.pop();
if (l > cur) {
cur = l;
ans.push_back(vector<int>());
}
if (cur % 2 == 0) ans[cur].push_back(node->val);
else ans[cur].insert(ans[cur].begin(),node->val);
if (node->left != NULL) {
level.push(cur+1);
q.push(node->left);
}
if (node->right != NULL) {
level.push(cur+1);
q.push(node->right);
}
}
return ans;
}
};