-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPractical05_ExpressionTree.cpp
More file actions
129 lines (122 loc) · 2.18 KB
/
Copy pathPractical05_ExpressionTree.cpp
File metadata and controls
129 lines (122 loc) · 2.18 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
120
121
122
123
124
125
126
127
128
129
#include <iostream>
using namespace std;
#include<string.h>
struct node
{
char data;
node *left;
node *right;
};
class tree
{ char prefix[20];
public: node *top;
void expression(char []);
void display(node *);
void non_rec_postorder(node *);
void del(node *);
};
class stack1
{
node *data[30];
int top;
public:
stack1()
{
top=-1;
}
int empty()
{
if(top==-1)
return 1;
return 0;
}
void push(node *p)
{
data[++top]=p;
}
node *pop()
{
return(data[top--]);
}
};
void tree::expression(char prefix[])
{
char c;
stack1 s;
node *t1,*t2;
int len,i;
len=strlen(prefix);
for(i=len-1;i>=0;i--)
{
top=new node;
top->left=NULL;
top->right=NULL;
if(isalpha(prefix[i]))
{
top->data=prefix[i];
s.push(top);
}
else if(prefix[i]=='+'||prefix[i]=='*'||prefix[i]=='-'||prefix[i]=='/')
{
t2=s.pop();
t1=s.pop();
top->data=prefix[i];
top->left=t2;
top->right=t1;
s.push(top);
}
}
top=s.pop();
}
void tree::display(node * root)
{
if(root!=NULL)
{ cout<<root->data;
display(root->left);
display(root->right);
}
}
void tree::non_rec_postorder(node *top)
{ stack1 s1,s2; /*stack s1 is being used for flag . A NULL data
implies that the right subtree has not been visited */
node *T=top;
cout<<"\n";
s1.push(T);
while(!s1.empty())
{
T=s1.pop();
s2.push(T);
if(T->left!=NULL)
s1.push(T->left);
if(T->right!=NULL)
s1.push(T->right);
}
while(!s2.empty())
{
top=s2.pop();
cout<<top->data;
}}
void tree::del(node* node)
{
if (node == NULL) return;
/* first delete both subtrees */
del(node->left);
del(node->right);
/* then delete the node */
cout<<" Deleting node:"<<node->data;
free(node);
}
int main()
{
char expr[20];
tree t;
cout<<"Enter prefix Expression: ";
cin>>expr;
cout<<expr;
t.expression(expr);
//t.display(t.top);
//cout<<endl;
t.non_rec_postorder(t.top);
// t.del(t.top);
// t.display(t.top);
}