-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0103.cpp
More file actions
executable file
·39 lines (35 loc) · 770 Bytes
/
LC0103.cpp
File metadata and controls
executable file
·39 lines (35 loc) · 770 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
Time: O(n)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
bool flip = false;
queue<TreeNode*> q;
vector<vector<int>> levels;
if (root)
q.push(root);
// level-order traversal
while (!q.empty()) {
int size = q.size();
vector<int> level;
while (size--) {
root = q.front();
q.pop();
level.push_back(root->val);
if (root->left)
q.push(root->left);
if (root->right)
q.push(root->right);
}
if (flip)
reverse(level.begin(), level.end());
levels.push_back(level);
flip ^= true;
}
return levels;
}
};