forked from iiitu-force/hacktoberfest22
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzigzagTraversalBinaryTree.cpp
More file actions
119 lines (88 loc) · 2.4 KB
/
Copy pathzigzagTraversalBinaryTree.cpp
File metadata and controls
119 lines (88 loc) · 2.4 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class BinaryTreeNode{
public:
T data;
BinaryTreeNode* left;
BinaryTreeNode* right;
BinaryTreeNode(T data){
this->data = data;
left = NULL;
right = NULL;
}
~BinaryTreeNode(){
delete left;
delete right;
}
};
BinaryTreeNode<int>* takeInputLevelWise(){
int rootdata;
cout<<"Enter root data: ";
cin>>rootdata;
if(rootdata==-1){
return NULL;
}
BinaryTreeNode<int>* root = new BinaryTreeNode<int>(rootdata);
queue<BinaryTreeNode<int>*> pendingNodes;
pendingNodes.push(root);
while(pendingNodes.size()!=0){
BinaryTreeNode<int>* front = pendingNodes.front();
pendingNodes.pop();
cout<<"Enter left child of "<<front->data<<endl;
int leftChild;
cin>>leftChild;
if(leftChild != -1){
BinaryTreeNode<int>* child = new BinaryTreeNode<int>(leftChild);
front->left = child;
pendingNodes.push(child);
}
cout<<"Enter right child of "<<front->data<<endl;
int rightChild;
cin>>rightChild;
if(rightChild != -1){
BinaryTreeNode<int>* child = new BinaryTreeNode<int>(rightChild);
front->right = child;
pendingNodes.push(child);
}
}
return root;
}
vector<vector<int>> zigzagLevelOrder(BinaryTreeNode<int>* root) {
vector<vector<int>> res;
if(root==NULL){
return res;
}
queue <BinaryTreeNode<int>*> q;
q.push(root);
bool leftToRight = true;
while(q.size()!=0){
int size = q.size();
vector <int> ans(size);
for(int i=0; i<size; i++){
BinaryTreeNode<int>* front = q.front();
q.pop();
int index = leftToRight ? i: size-i-1;
ans[index] = front->data;
if(front->left!=NULL){
q.push(front->left);
}
if(front->right!=NULL){
q.push(front->right);
}
}
res.push_back(ans);
leftToRight = !leftToRight;
}
return res;
}
int main(int argc, char const *argv[]) {
BinaryTreeNode<int>* root = takeInputLevelWise();
vector<vector<int>> vec = zigzagLevelOrder(root);
for (int i = 0; i < vec.size(); i++) {
for (int j = 0; j < vec[i].size(); j++)
cout << vec[i][j] << " ";
cout << endl;
}
return 0;
}