-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathexpression-tree.py
148 lines (101 loc) · 3.18 KB
/
expression-tree.py
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
137
138
139
140
141
142
143
144
145
146
147
# Copyright (C) Deepali Srivastava - All Rights Reserved
# This code is part of DSA course available on CourseGalaxy.com
class Node:
def __init__(self,value):
self.info = value
self.lchild = None
self.rchild = None
class ExpressionTree:
def __init__(self):
self.root = None
def buildTree(self, postfix):
from queue import LifoQueue
stack = LifoQueue()
for i in range(len(postfix)):
if isOperator( postfix[i] ):
t = Node( postfix[i] )
t.rchild = stack.get()
t.lchild = stack.get()
stack.put(t)
else: # operand
t = Node(postfix[i])
stack.put(t)
self.root = stack.get()
def prefix(self):
self._preorder(self.root)
print()
def _preorder(self, p):
if p == None:
return
print(p.info, end = " ")
self._preorder(p.lchild)
self._preorder(p.rchild)
def postfix(self):
self._postorder(self.root)
print()
def _postorder(self,p):
if p == None:
return
self._postorder(p.lchild)
self._postorder(p.rchild)
print(p.info, end = " ")
def parenthesizedInfix(self):
self._inorder(self.root)
print()
def _inorder(self, p):
if p == None:
return
if isOperator(p.info):
print("(", end = "")
self._inorder(p.lchild)
print(p.info, end = " ")
self._inorder(p.rchild)
if isOperator(p.info):
print(")",end = "")
def display(self):
self._display(self.root,0)
print()
def _display(self,p,level):
if p is None:
return
self._display(p.rchild, level+1)
print()
for i in range(level):
print(" ", end='')
print(p.info)
self._display(p.lchild, level+1)
def evaluate(self):
if self.root == None:
return 0
else:
return self._evaluate(self.root)
def _evaluate(self, p):
if not isOperator(p.info) :
return ord(p.info)-48
leftValue = self._evaluate(p.lchild)
rightValue = self._evaluate(p.rchild)
if p.info=='+':
return leftValue + rightValue
elif p.info=='-':
return leftValue - rightValue
elif p.info=='*':
return leftValue * rightValue
else:
return leftValue // rightValue
def isOperator(c):
if c == '+' or c == '-' or c == '*' or c == '/' or c == '^':
return True
return False
##############################################################################################
if __name__ == '__main__':
tree = ExpressionTree()
postfix = "54+12*3*-"
tree.buildTree(postfix)
tree.display()
print("Prefix : ")
tree.prefix()
print("Postfix : ")
tree.postfix()
print("Infix : ")
tree.parenthesizedInfix()
print("Value : " , tree.evaluate() )