-
Notifications
You must be signed in to change notification settings - Fork 0
/
Expression_tree.cpp
136 lines (113 loc) · 2.83 KB
/
Expression_tree.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
//by Sushant Gaurav
#include <bits/stdc++.h>
#include <vector>
using namespace std;
struct treenode
{
char info;
struct treenode *left;
struct treenode *right;
};
struct treenode* create(char data)
{
struct treenode *root = new treenode;
root->info = data;
root->left = NULL;
root->right = NULL;
return root;
}
struct treenode* preordercreate(vector <char> v , int &index)
{
if( index == v.size() )
return NULL;
struct treenode *newnode = new treenode;
newnode = create(v[index]);
index++;
if(v[index] == '+' || v[index] == '-' || v[index] == '*' || v[index] == '/')
{
newnode->left = preordercreate(v , index);
newnode->right = preordercreate(v, index);
return newnode;
}
else
{
return newnode;
}
}
struct treenode* postordercreate(vector <char> v , int &index)
{
if( index < 0 )
return NULL;
struct treenode *newnode = create(v[index]);
index--;
if(v[index] == '+' || v[index] == '-' || v[index] == '*' || v[index] == '/')
{
newnode->right = postordercreate(v, index);
newnode->left = postordercreate(v , index);
}
return newnode;
}
void preorder(struct treenode *root)
{
if(root == NULL)
return;
cout<<root->info<<" ";
preorder(root->left);
preorder(root->right);
}
int main()
{
int choice,n;
char data;
vector <char> v1,v2;
struct treenode *root = NULL;
while(1)
{
cout<<"\n1. Create expression tree from pre-order"<<endl;
cout<<"2. Create expression tree from post-order"<<endl;
cout<<"3. Traverse the tree (pre-order)"<<endl;
cout<<"4. EXIT"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
{
cout<<"\nEnter the size of expression : ";
cin>>n;
cout<<"\nEnter the pre-order : ";
for(int i=0 ; i<n ; i++)
{
cin>>data;
v1.push_back(data);
}
n = 0;
root = preordercreate(v1 , n);
break;
}
case 2:
{
cout<<"\nEnter the size of expression : ";
cin>>n;
cout<<"\nEnter the post-order : ";
for(int i=0 ; i<n ; i++)
{
cin>>data;
v2.push_back(data);
}
n = n-1;
root = postordercreate(v2 , n);
break;
}
case 3:
cout<<"\nPreorder order is : ";
preorder(root);
break;
case 4:
exit(0);
break;
default:
cout<<"\nINVALID CHOICE"<<endl;
}
}
}