-
Notifications
You must be signed in to change notification settings - Fork 0
/
buildTree_noSpaces.py
55 lines (43 loc) · 1.51 KB
/
buildTree_noSpaces.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
from pythonds.basic.stack import Stack
from pythonds.trees.binaryTree import BinaryTree
def buildParseTree(fpexp):
##code so you don't need to uses spaces to split the fpexp
fplist = []
numberinstring = ""
for token in fpexp:
if(token not in ['(','+', '-', '*', '/',')']):
numberinstring = numberinstring + token
if token == "(":
fplist.append(token)
if token in ['(','+', '-', '*', '/',')']:
if token == '*':
fplist.append(token)
if(numberinstring != ""):
fplist.append(numberinstring)
numberinstring = ""
fplist.append(token)
pStack = Stack()
eTree = BinaryTree('')
pStack.push(eTree)
currentTree = eTree
for i in fplist:
if i == '(':
currentTree.insertLeft('')
pStack.push(currentTree)
currentTree = currentTree.getLeftChild()
elif i not in ['+', '-', '*', '/', ')']:
currentTree.setRootVal(int(i))
parent = pStack.pop()
currentTree = parent
elif i in ['+', '-', '*', '/']:
currentTree.setRootVal(i)
currentTree.insertRight('')
pStack.push(currentTree)
currentTree = currentTree.getRightChild()
elif i == ')':
currentTree = pStack.pop()
else:
raise ValueError
return eTree
##withoutSpaces
pt = buildParseTree("((10+5)*3)")