forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
33 lines (33 loc) · 949 Bytes
/
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
/**
* 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) {
if (!root) return {};
vector<vector<int>> res;
queue<TreeNode*> q{{root}};
bool leftToRight = true;
while (!q.empty()) {
int size = q.size();
vector<int> oneLevel(size);
for (int i = 0; i < size; ++i) {
TreeNode* t = q.front();
q.pop();
int idx = leftToRight ? i : (size - 1 - i);
oneLevel[idx] = t->val;
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
leftToRight = !leftToRight;
res.push_back(oneLevel);
}
return res;
}
};