-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExpTree.py
70 lines (52 loc) · 1.38 KB
/
ExpTree.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
class Node:
def __init__(self, data, leftChild=None, rightChild=None, parent=None):
self.data = data
self.left = leftChild
self.right = rightChild
self.parent = parent
class Stack:
def __init__(self):
self.data = []
def push(self, data):
self.data.append(data)
def pop(self):
return self.data.pop()
class ExpTree:
def __init__(self, root=None):
self.root = root
def parseInfix(self, exp):
stack = Stack()
b = Node() # branch
for ch in exp:
if ch == '(': # Go left on (
b = b.left
continue
if ch == ')': # Go up on )
b = b.parent
continue
if isOperator(ch): # Set data on op
continue
if not isOperator(ch): # Set leaf on operand
stack.push(ch)
def parsePrefix(self, exp):
pass
def parsePostfix(self, exp):
pass
def printInOrder(self):
pass
def printPreOrder(self):
pass
def printPostOrder(self):
pass
def isOperator(ch):
return ch in ['+', '-', '*', '/']
def main():
print('Starting...')
exp = '(2+3)'
tree = ExpTree()
tree.parseInOrder(exp)
tree.printPreOrder()
tree.printPostOrder()
print('Done!')
if __name__ == '__main__':
main()