-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzigzag_traversal_tree.cpp
73 lines (67 loc) · 2.26 KB
/
zigzag_traversal_tree.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* 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>> usingTwoStack(TreeNode* root) {
vector<vector<int>> ans;
int flag = 1;
stack<TreeNode*>odd, even;
if(root != NULL) odd.push(root);
while(!odd.empty() || !even.empty()) {
vector<int>v;
if(flag%2) {
v.clear();
int _size = odd.size();
for (int i=0;i<_size;i++) {
TreeNode* curr = odd.top();
odd.pop();
v.push_back(curr->val);
if(curr->left != NULL) even.push(curr->left);
if(curr->right != NULL) even.push(curr->right);
}
} else {
v.clear();
int _size = even.size();
for (int i=0;i<_size;i++) {
TreeNode* curr = even.top();
even.pop();
v.push_back(curr->val);
if(curr->left != NULL) odd.push(curr->left);
if(curr->right != NULL) odd.push(curr->right);
}
}
ans.push_back(v);
}
return ans;
}
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>>ans;
queue<TreeNode*>q;
bool flag = true;
if(root != NULL) q.push(root);
while(!q.empty()) {
int _size = q.size();
vector<int>temp(_size);
for (int i=0;i<_size;i++) {
TreeNode* curr = q.front();
q.pop();
int index = flag ? i : _size - i - 1;
temp[index] = curr->val;
if(curr->left != NULL) q.push(curr->left);
if(curr->right != NULL) q.push(curr->right);
}
ans.push_back(temp);
flag = !flag;
}
return ans;
}
};