-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path103. Binary Tree Zigzag Level Order Traversal
More file actions
94 lines (79 loc) · 2.39 KB
/
103. Binary Tree Zigzag Level Order Traversal
File metadata and controls
94 lines (79 loc) · 2.39 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
if(!root)
return {};
vector<vector<int>> ans;
queue<TreeNode*> q;
q.push(root);
int sw = 0;
while(!q.empty()) {
int s = q.size();
vector<int> tmp;
while(s--) {
TreeNode* cur = q.front(); q.pop();
tmp.push_back(cur->val);
if(cur->left)
q.push(cur->left);
if(cur->right)
q.push(cur->right);
}
if(sw)
reverse(tmp.begin(), tmp.end());
ans.push_back(tmp);
sw = (sw + 1) % 2;
}
return ans;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
if(not root)
return {};
queue<TreeNode*> q;
q.push(root);
int sw = 0;
vector<vector<int>> ans;
while(not q.empty()) {
int s = q.size();
vector<int> tmp;
while(s--) {
TreeNode* cur = q.front(); q.pop();
if(sw % 2)
tmp.insert(tmp.begin(), cur->val);
else
tmp.push_back(cur->val);
if(cur->left)
q.push(cur->left);
if(cur->right)
q.push(cur->right);
}
sw++;
ans.push_back(tmp);
}
return ans;
}
};