-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzigzag_traversal.cpp
More file actions
104 lines (85 loc) · 2.03 KB
/
Copy pathzigzag_traversal.cpp
File metadata and controls
104 lines (85 loc) · 2.03 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
95
96
97
98
99
100
101
102
103
104
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
struct Node{
int data;
Node* right;
Node* left;
Node(int val)
{
data=val;
right=left=NULL;
}
};
//zigzag Traversar(----- left to right ------- right to left------)
vector<vector<int>> ZigZag_LevelOrde(Node* root)
{
vector<vector<int>>ans;
if(root==NULL)return ans;
queue<Node*>q;
q.push(root);
bool is=false;
while(!q.empty())
{
int n=q.size();
vector<int>dummy;
for(int i=1;i<=n;i++)
{
Node* temp=q.front();
q.pop();
if(temp->left!=NULL)q.push(temp->left);
if(temp->right!=NULL)q.push(temp->right);
dummy.push_back(temp->data);
}
//just implement in Level order Traverser when you at odd Level reverse it
if(!is)//true for odd
reverse(dummy.begin(),dummy.end());
ans.push_back(dummy);
is=!is;//reset it for even
}
return ans;
}
void Print_solution(vector<vector<int>>ans)
{
for(int i=0;i<ans.size();i++)
{
for(int j=0;j<ans[i].size();j++)
{
cout<<ans[i][j]<<" ";
}
cout<<" "<<","<<" ";
}
}
int main()
{
Node* root=new Node(1);
root->left=new Node(2);
root->left->left=new Node(10);
root->right=new Node(3);
root->right->right=new Node(4);
root->right->left=new Node(9);
root->right->right->left=new Node(15);
root->right->right->right=new Node(5);
root->right->right->right->left=new Node(6);
root->right->right->right->left->right=new Node(7);
vector<vector<int>>nums=ZigZag_LevelOrde(root);
cout<<"Zigzag traversal:";
Print_solution(nums);
cout<<endl;
return 0;
}
/* Tree view
1
/ \
2 3
/ / \
10 9 4
/ \
15 5
/
6
\
7
*/