-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostfixTREE.cpp
112 lines (108 loc) · 2.42 KB
/
postfixTREE.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
#include <iostream>
using namespace std;
class PF;
class node
{
char data;
node *left;
node *right;
friend class PF;
};
class PF{
public:
char postfix[35];
int top = -1;
node *arr[35];
int r(char inputchar)
{
if (inputchar == '+' || inputchar == '-' || inputchar == '*' || inputchar== '/')
return (-1);
else if (inputchar >= 'a' || inputchar <= 'z')
return (1);
else if (inputchar >= 'A' || inputchar <= 'Z')
return (1);
else
return (-99); //for error
}
void push(node *tree)
{
top++;
arr[top] = tree;
}
node *pop()
{
top--;
return (arr[top + 1]);
}
void create_expr_tree(char *suffix)
{
char symbol;
node *newl, *ptr1, *ptr2;
int flag; //flag=-1 when operator and flag=1 when operand
symbol = suffix[0]; //Read the first symbol from the postfix expr.
for (int i = 1; symbol != NULL; i++)
{ //continue till end of the expr.
flag = r(symbol); //check symbol is operand or operator.
if (flag == 1)//if symbol is operand.
{
newl = new node;
newl->data = symbol;
newl->left = NULL;
newl->right = NULL;
push(newl);
}
else
{ //If the symbol is operator//pop two top elements.
ptr1 = pop();
ptr2 = pop();
newl = new node;
newl->data = symbol;
newl->left = ptr2;
newl->right = ptr1;
push(newl);
}
symbol = suffix[i];
}
}
void preOrder(node *tree)
{
if (tree != NULL)
{
cout << tree->data;
preOrder(tree->left);
preOrder(tree->right);
}
}
void inOrder(node *tree)
{
if (tree != NULL)
{
inOrder(tree->left);
cout << tree->data;
inOrder(tree->right);
}
}
void postOrder(node *tree)
{
if (tree != NULL)
{
postOrder(tree->left);
postOrder(tree->right);
cout << tree->data;
}
}
};
int main()
{ PF p;
node* arr[35];char *postfix;
cout << "Enter Postfix Expression : ";
cin >>postfix;
p.create_expr_tree(postfix);
cout << "\nIn-Order Traversal : ";
p.inOrder(arr[0]);
cout << "\nPre-Order Traversal : ";
p.preOrder(arr[0]);
cout << "\nPost-Order Traversal : ";
p.postOrder(arr[0]);
return 0;
}