Skip to content

Commit 12f46a1

Browse files
authored
Create tree from Inorder and Preorder
1 parent 724dc77 commit 12f46a1

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
/* Hacker Blocks */
2+
/* Title - Level Order (ZigZag) */
3+
/* Created By - Akash Modak */
4+
/* Date - 19/09/2020 */
5+
6+
// Given preorder and inorder create the tree
7+
8+
// Input Format
9+
// Enter the size of the preorder array N then add N more elements and store in the array denoting the preorder traversal of the tree. Then enter the size of the inorder array M and add M more elements and store the inorder traversal of the array.
10+
11+
// Constraints
12+
// 1 <= N, M <= 10^4
13+
14+
// Output Format
15+
// Display the tree using a modified preorder function. For each node , first print its left child's data , then the data of the root itself , then the data of its right child. Do this for each node in a new line in preorder manner. If one of the children does not exist print END in its place. Refer to the sample testcase.
16+
17+
// Sample Input
18+
// 3
19+
// 1 2 3
20+
// 3
21+
// 3 2 1
22+
// Sample Output
23+
// 2 => 1 <= END
24+
// 3 => 2 <= END
25+
// END => 3 <= END
26+
// Explanation
27+
// The above tree looks like
28+
29+
// 1
30+
// /
31+
// 2
32+
// /
33+
// 3
34+
35+
#include<bits/stdc++.h>
36+
using namespace std;
37+
class node{
38+
public:
39+
int data;
40+
node *left,*right;
41+
node(int d){
42+
data = d;
43+
left=right=NULL;
44+
}
45+
};
46+
47+
node* build(int pre[],int in[],int start,int end,int &preIndex){
48+
if(start>end){
49+
return NULL;
50+
}
51+
52+
node* root = new node(pre[preIndex]);
53+
54+
int i;
55+
for(i=start;i<=end;i++)
56+
if(pre[preIndex]==in[i])
57+
break;
58+
preIndex++;
59+
root->left = build(pre,in,start,i-1,preIndex);
60+
root->right = build(pre,in,i+1,end,preIndex);
61+
return root;
62+
}
63+
void modifiedPreorder(node* root){
64+
if(root==NULL)
65+
return;
66+
if(root->left)
67+
cout<<root->left->data<<" => ";
68+
else
69+
cout<<"END => ";
70+
cout<<root->data;
71+
if(root->right)
72+
cout<<" <= "<<root->right->data<<endl;
73+
else
74+
cout<<" <= END "<<endl;
75+
76+
modifiedPreorder(root->left);
77+
modifiedPreorder(root->right);
78+
return;
79+
}
80+
int main() {
81+
int n;
82+
cin>>n;
83+
int pre[n],in[n];
84+
for(int i=0;i<n;i++)
85+
cin>>pre[i];
86+
87+
cin>>n;
88+
for(int i=0;i<n;i++)
89+
cin>>in[i];
90+
// for(int i=0;i<n;i++)
91+
// cout<<in[i]<<" ";
92+
// cout<<endl;
93+
int m=0;
94+
node* root=build(pre,in,0,n-1,m);
95+
// cout<<root->data;
96+
modifiedPreorder(root);
97+
return 0;
98+
}

0 commit comments

Comments
 (0)