Binary Tree Zigzag Level Order Traversal LeetCode solution in C++

1
class Solution {
2
public:
3
vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
4
vector<vector<int>> ans;
5
if (!root) return ans;
6
vector<int> r;
7
queue<TreeNode *> q;
8
int count = 1;
9
q.push(root);
10
q.push(NULL);
11
while (1) {
12
if (q.front() == NULL) {
13
q.pop();
14
if (count % 2 == 0) reverse(r.begin(), r.end());
15
ans.push_back(r);
16
if (q.empty()) return ans;
17
q.push(NULL);
18
r.resize(0);
19
count++;
20
continue;
21
}
22

23
r.push_back((q.front())->val);
24
if (q.front()->left) q.push((q.front())->left);
25
if (q.front()->right) q.push((q.front())->right);
26

27
q.pop();
28
}
29
return ans;
30
}
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0