-
Notifications
You must be signed in to change notification settings - Fork 0
/
expression_tree.py
81 lines (62 loc) · 1.67 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
class stack:
def __init__(self):
self.arr = []
def push(self, data):
self.arr.append(data)
def pop(self):
try:
return self.arr.pop(-1)
except:
pass
def top(self):
try:
return self.arr[-1]
except:
pass
def size(self):
return len(self.arr)
class node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
class exp_tree:
def __init__(self,postfix_exp):
self.exp = postfix_exp
self.root = None
self.createTree(self.exp)
def isOperator(self, char):
optr = [' ', '-', '*', '/', '^']
if char in optr:
return True
return False
def createTree(self, exp):
s = stack()
self.root = node(exp[-1])
s.push(self.root)
for i in "".join(reversed(exp[:-1])):
curr_node = s.top()
if not curr_node.right:
temp = node(i)
curr_node.right = temp
if self.isOperator(i):
s.push(temp)
else:
temp = node(i)
curr_node.left = temp
s.pop()
if self.isOperator(i):
s.push(temp)
def inOrder(self,head):
if head.left:
self.inOrder(head.left)
print(head.data,end=" ")
if head.right:
self.inOrder(head.right)
def infixExp(self):
self.inOrder(self.root)
print()
if __name__=="__main__":
postfixExp = "ab ef*g*-"
et = exp_tree(postfixExp)
et.infixExp()