-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzigzagLevelOrder.cpp
40 lines (30 loc) · 1.03 KB
/
zigzagLevelOrder.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
34
35
36
37
38
39
40
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ans; // Correct type for the return value
if (root == nullptr) return ans;
queue<TreeNode*> q;
q.push(root);
bool leftToRight = true;
while (!q.empty()) {
int size = q.size();
vector<int> temp(size);
for (int i = 0; i < size; i++) {
TreeNode* frontnode = q.front();
q.pop();
int index = leftToRight ? i : size - 1 - i;
temp[index] = frontnode->val;
// Add child nodes to the queue
if (frontnode->left) {
q.push(frontnode->left);
}
if (frontnode->right) {
q.push(frontnode->right);
}
}
leftToRight = !leftToRight;
ans.push_back(temp);
}
return ans;
}
};