def buildexpressionTree(exp):
tree=BinaryTree('')
stack=[]
stack.append(tree)
currentTree=tree
for i in exp:
if i=='(':
currentTree.insertLeft('')
stack.append(currentTree)
currentTree=currentTree.leftChild
elif i not in '+-*/()':
currentTree.key=int(i)
parent=stack.pop()
currentTree=parent
elif i in '+-*/':
currentTree.key=i
currentTree.insertRight('')
stack.append(currentTree)
currentTree=currentTree.rightChild
elif i==')':
currentTree=stack.pop()
else:
raise ValueError
return tree
def build_tree_with_post(exp):
stack=[]
oper='+-*/'
for i in exp:
if i not in oper:
tree=BinaryTree(int(i))
stack.append(tree)
else:
righttree=stack.pop()
lefttree=stack.pop()
tree=BinaryTree(i)
tree.leftChild=lefttree
tree.rightChild=righttree
stack.append(tree)
return stack.pop() 3.树的遍历 3.1 先序遍历(preorder travelsal)
先打印出根,然后递归的打印出左子树、右子树,对应先缀表达式
def preorder(tree,nodelist=None):
if nodelist is None:
nodelist=[]
if tree:
nodelist.append(tree.key)
preorder(tree.leftChild,nodelist)
preorder(tree.rightChild,nodelist)
return nodelist