import operator
import BinaryTree
from stackpractise import stack
def buildparsetree(fpexp):
tree=BinaryTree('')
s=stack()
current=tree
for i in fpexp:
if i == '(':
s.push(current)
current.insertleft('')
current=current.getleftchild()
elif i not in '+-*/)':
current.setrootval(int(i))
current=s.pop()
elif i in '+-*/':
current.setrootval(i)
current.insertright('')
s.push(current)
current=current.getrightchild()
elif i == ')':
current=s.pop()
else:
return False
return tree
def evluate(parsetree):
opers={'+':operator.add,'-':operator.sub,'*':operator.mul,'/':operator.truediv()}
leftc=parsetree.getleftchild()
rightc=parsetree.getrightchild()
if leftc and rightc:
fn=opers[parsetree.getrootval()]
return fn(evluate(leftc),evluate(rightc))
else:
return parsetree.getrootval()
t=buildparsetree('(1+(2+3)')
print(evluate(t))
Traceback (most recent call last):
File "D:\pythonwork\Tree\构建解析树.py", line 39, in <module>
t=buildparsetree('(1+(2+3)')
File "D:\pythonwork\Tree\构建解析树.py", line 6, in buildparsetree
tree=BinaryTree('')
TypeError: 'module' object is not callable