Skip to content

Commit 1953d5e

Browse files
authored
Level Order (ZigZag)
1 parent d2ca4b7 commit 1953d5e

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/* Hacker Blocks */
2+
/* Title - Level Order (ZigZag) */
3+
/* Created By - Akash Modak */
4+
/* Date - 19/09/2020 */
5+
6+
// Given a binary tree. Print the zig zag order i.e print level 1 from left to right, level 2 from right to left and so on. This means odd levels should get printed from left to right and even levels should be printed from right to left.
7+
8+
// Input Format
9+
// Enter the values of all the nodes in the binary tree in pre-order format where true suggest the node exists and false suggests it is NULL
10+
11+
// Constraints
12+
// None
13+
14+
// Output Format
15+
// Display the values in zigzag level order in which each value is separated by a space
16+
17+
// Sample Input
18+
// 10 true 20 true 40 false false true 50 false false true 30 true 60 false false true 73 false false
19+
// Sample Output
20+
// 10 30 20 40 50 60 73
21+
22+
#include<bits/stdc++.h>
23+
using namespace std;
24+
class node{
25+
public:
26+
int data;
27+
node *left,*right;
28+
node(int d){
29+
data = d;
30+
left=right=NULL;
31+
}
32+
};
33+
node* build(string s){
34+
if(s=="true"){
35+
int d;
36+
cin>>d;
37+
node *root = new node(d);
38+
string l;
39+
cin>>l;
40+
if(l=="true")
41+
root->left = build(l);
42+
string r;
43+
cin>>r;
44+
if(r=="true")
45+
root->right = build(r);
46+
return root;
47+
}
48+
return NULL;
49+
}
50+
void zigzag(node* root){
51+
queue<node*> q;
52+
q.push(root);
53+
bool flag = true;
54+
while(!q.empty()){
55+
vector<int> v;
56+
int s = q.size();
57+
while(s--){
58+
node *temp = q.front();
59+
q.pop();
60+
v.push_back(temp->data);
61+
if(temp->left)
62+
q.push(temp->left);
63+
if(temp->right)
64+
q.push(temp->right);
65+
}
66+
if(!flag)
67+
reverse(v.begin(),v.end());
68+
for(auto x: v)
69+
cout<<x<<" ";
70+
flag= !flag;
71+
}
72+
}
73+
int main() {
74+
node* root=build("true");
75+
zigzag(root);
76+
return 0;
77+
}

0 commit comments

Comments
 (0)