-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExpressionTree.cpp
118 lines (108 loc) · 2 KB
/
ExpressionTree.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
#include <iostream>
using namespace std;
class TreeNode
{
public:
char data;
TreeNode *lChild, *rChild;
TreeNode(char data, TreeNode *left = NULL, TreeNode *right = NULL)
{
this->data = data;
this->lChild = left;
this->rChild = right;
}
};
class Stack
{
public:
TreeNode *treeNode;
Stack *next;
Stack(TreeNode *treeNode)
{
this->treeNode = treeNode;
next = NULL;
}
};
class ExpressionTree
{
private:
Stack *top;
public:
ExpressionTree()
{
top = NULL;
}
void push(TreeNode *ptr)
{
if (top == NULL)
top = new Stack(ptr);
else
{
Stack *nptr = new Stack(ptr);
nptr->next = top;
top = nptr;
}
}
TreeNode *pop()
{
TreeNode *ptr = top->treeNode;
top = top->next;
return ptr;
}
TreeNode *peek()
{
return top->treeNode;
}
// function to insert character
void insert(char val)
{
// If the encountered character is Number make a node an push it on stack
if (isOperand(val))
{
TreeNode *nptr = new TreeNode(val);
push(nptr);
}
// else if it is operator then make a node and left and
else if (isOperator(val))
{
TreeNode *nptr = new TreeNode(val);
nptr->lChild = pop();
nptr->rChild = pop();
push(nptr);
}
}
bool isOperand(char ch)
{
return ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z';
}
bool isOperator(char ch)
{
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
// function to construct expression Tree
void construct(string eqn)
{
for (int i = eqn.length() - 1; i >= 0; i--)
insert(eqn[i]);
}
void inOrder(TreeNode *ptr)
{
if (ptr != NULL)
{
inOrder(ptr->lChild);
cout << ptr->data;
inOrder(ptr->rChild);
}
}
};
int main()
{
string exp;
ExpressionTree et;
cout << "Enter expression in Prefix form: ";
cin >> exp;
et.construct(exp);
cout << "In-order Traversal of Expression Tree : ";
et.inOrder(et.peek());
return 0;
};