-
Notifications
You must be signed in to change notification settings - Fork 0
/
bst_zigzag_level_traversal.cc
47 lines (44 loc) · 1.06 KB
/
bst_zigzag_level_traversal.cc
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
46
47
#include<queue>
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ans;
if(!root){
return ans;
}
queue<TreeNode*> q;
q.push(root);
q.push(NULL);
TreeNode* temp;
vector<int> level;
while(!q.empty()){
temp = q.front();
q.pop();
if(temp==NULL){
ans.push_back(level);
level.clear();
if(q.empty()){
break;
}
q.push(NULL);
}
else{
level.push_back(temp->val);
if(temp->left){
q.push(temp->left);
}
if(temp->right){
q.push(temp->right);
}
}
}
int i = 0;
for(vector<int> &v: ans){
if(i%2==1){
reverse(v.begin(), v.end());
}
i++;
}
return ans;
}
};