-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbinary-tree-zigzag-level-order-traversal.cpp
More file actions
45 lines (37 loc) · 1.07 KB
/
Copy pathbinary-tree-zigzag-level-order-traversal.cpp
File metadata and controls
45 lines (37 loc) · 1.07 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
//Runtime: 3 ms
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int> > res;
if(!root) return res;
queue<pair<int, TreeNode* > >Q;
Q.push(make_pair(0, root));
vector<int> tmp;
int maxlvl = 0;
while(!Q.empty())
{
pair<int, TreeNode*> t = Q.front();
Q.pop();
if(t.first > maxlvl)
{
maxlvl++;
if(tmp.size() > 0)
{
if(maxlvl%2!=1)
reverse(tmp.begin(), tmp.end());
res.push_back(tmp);
}
tmp.clear();
}
tmp.push_back(t.second->val);
if(t.second->left) Q.push(make_pair(t.first+1, t.second->left));
if(t.second->right) Q.push(make_pair(t.first+1, t.second->right));
}
if(tmp.size() > 0)
{
if(maxlvl%2!=0)reverse(tmp.begin(), tmp.end());
res.push_back(tmp);
}
return res;
}
};