-
Notifications
You must be signed in to change notification settings - Fork 64
/
BinaryTreeZigZagLevelOrderTraversal.cpp
113 lines (109 loc) · 2.73 KB
/
BinaryTreeZigZagLevelOrderTraversal.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/**
* 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)
{
// Method-1 (Using Queue)
if (!root)
{
return {};
}
vector<vector<int>> res;
queue<TreeNode *> q;
q.push(root);
int x = 0;
while (!q.empty())
{
vector<int> temp;
int size = q.size();
for (int i = 0; i < size; ++i)
{
TreeNode *curr = q.front();
q.pop();
temp.push_back(curr->val);
if (curr->left)
{
q.push(curr->left);
}
if (curr->right)
{
q.push(curr->right);
}
}
if (x % 2 == 0)
{
res.push_back(temp);
x++;
}
else
{
reverse(temp.begin(), temp.end());
res.push_back(temp);
x++;
}
}
return res;
// Method-2(Using stack)
vector<vector<int>> ans;
if (root == NULL)
{
return {};
}
stack<TreeNode *> p;
stack<TreeNode *> q;
p.push(root);
while (p.size() != 0 || q.size() != 0)
{
vector<int> v;
while (p.size() != 0)
{
TreeNode *curr = p.top();
v.push_back(curr->val);
p.pop();
if (curr->left != NULL)
{
q.push(curr->left);
}
if (curr->right != NULL)
{
q.push(curr->right);
}
}
if (!v.empty())
{
ans.push_back(v);
}
vector<int> t;
while (q.size() != 0)
{
TreeNode *curr = q.top();
t.push_back(curr->val);
q.pop();
if (curr->right != NULL)
{
p.push(curr->right);
}
if (curr->left != NULL)
{
p.push(curr->left);
}
}
if (!t.empty())
{
ans.push_back(t);
}
}
return ans;
}
};