按照顺序依次进行即可
def preorder(tree):
if tree:
print(tree.getRootVal())
preorder(tree.getLeftChild())
preorder(tree.getRightChild())
def postorder(tree):
if tree:
postorder(tree.getLeftChild())
postorder(tree.getRightChild())
print(tree.getRootVal())
def inorder(tree):
if tree:
inorder(tree.getLeftChild())
print(tree.getRootVal())
inorder(tree.getRightChild())
需要加入子树是否为空的判断
def preorder(self):
print(self.key)
if self.leftChild:
self.leftChild.preorder()
if self.rightChild:
self.rightChild.preorder()
def postordereval(tree):
opers = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}
if tree:
# 左子树
res1 = postordereval(tree.getLeftChild())
# 右子树
res2 = postordereval(tree.getRightChild())
if res1 and res2:
# 根节点
return opers[tree.getRootVal()](res1, res2)
else:
return tree.getRootVal()
下列代码中对每个数字也加了括号,请自行修改代码去除(课后练习)
def printexp(tree):
sVal = ""
if tree:
sVal = '(' + printexp(tree.getLeftChild())
sVal = sVal + str(tree.getRootVal())
sVal = sVal + printexp(tree.getRightChild()) + ')'
return sVal