-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpression.cpp
More file actions
112 lines (107 loc) · 2.44 KB
/
Copy pathexpression.cpp
File metadata and controls
112 lines (107 loc) · 2.44 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
#include<iostream>
#include<string.h>
using namespace std;
struct node{
char data;
node* left;
node* right;
};
class Stack{
node* s[20];
int top=-1;
public:
void push(node* t){
s[++top]=t;
};
node* pop(){
return s[top--];
};
int isempty(){
if(top==-1){
return 1;
}
return 0;
}
};
class ExpTree{
char prefix[20];
node* top=nullptr;
public:
void expression(char prefix[]);
void inorder(node* t){
if(t==NULL){return;}
inorder(t->left);
cout<<t->data;
inorder(t->right);
}
void postorder(node *tm){
if(tm==NULL){return;}
Stack s1,s2;
s1.push(tm);
while(!s1.isempty()){
node* temp=s1.pop();
s2.push(temp);
if(temp->left){
s1.push(temp->left);
}
if(temp->right){
s1.push(temp->right);
}
while(!s2.isempty()){
node* t=s2.pop();
cout<<t->data;
}
}
}
void display(){
cout<<"Display Postorder Sequence:";
postorder(top);
cout<<endl;
cout<<"Display inorder Sequence:";
inorder(top);
cout<<endl;
cout<<"Deleting Nodes From Tree"<<endl;
DelTree(top);
cout<<"Tree Deleted Sucessfully";
}
void DelTree(node* t){
if(t==NULL){
return;
}
DelTree(t->left);
DelTree(t->right);
cout<<t->data<<" is deleted"<<endl;
delete t;
}
};
void ExpTree::expression(char prefix[]){
Stack s1;
node *d1,*d2;
int len=strlen(prefix);
for(int i=len;i>=0;i--){
if(isalpha(prefix[i])){
node *top=new node;
top->left=NULL;
top->right=NULL;
top->data=prefix[i];
s1.push(top);
}else if(prefix[i]=='+'||prefix[i]=='-'||prefix[i]=='*'||prefix[i]=='/'){
d1=s1.pop();
d2=s1.pop();
node *top=new node;
top->data=prefix[i];
top->left=d1;
top->right=d2;
s1.push(top);
}
}
top=s1.pop();
}
int main(){
ExpTree t;
char ch[20];
cout<<"enter the expression"<<endl;
cin>>ch;
t.expression(ch);
t.display();
}