-
Notifications
You must be signed in to change notification settings - Fork 1
/
103_Binary_Tree_Zigzag_Level_Order_Traversal.cpp
53 lines (44 loc) · 1.38 KB
/
103_Binary_Tree_Zigzag_Level_Order_Traversal.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
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ans;
if(root == NULL) return ans;
queue<TreeNode*> q;
queue<int> lq;
q.push(root);
lq.push(1);
while(!q.empty()){
TreeNode* cur_node = q.front();
int cur_val = q.front()->val;
int cur_level = lq.front();
q.pop();
lq.pop();
if(ans.size() < cur_level){
vector<int> temp;
ans.push_back(temp);
}
ans[cur_level - 1].push_back(cur_val);
if(cur_node->left != NULL){
q.push(cur_node->left);
lq.push(cur_level + 1);
}
if(cur_node->right != NULL){
q.push(cur_node->right);
lq.push(cur_level + 1);
}
}
for(int i = 0; i < ans.size(); i++){
if( i % 2 == 1) reverse(ans[i].begin(), ans[i].end());
}
return ans;
}
};