先给出二叉树节点的python表示:
class Node: def __init__(self,value=None,left=None,right=None): self.value=value self.left=left self.right=right
def preTraverse(root): if root==None: return print(root.value) preTraverse(root.left) preTraverse(root.right) def midTraverse(root): if root==None: return midTraverse(root.left) print(root.value) midTraverse(root.right) def afterTraverse(root): if root==None: return afterTraverse(root.left) afterTraverse(root.right) print(root.value)
现在假设搞一个二叉树为(ps:ubuntu的Libre Draw还真好用~哈哈):
if __name__=='__main__': root=Node('D',Node('B',Node('A'),Node('C')),Node('E',right=Node('G',Node('F')))) print('前序遍历:') preTraverse(root) print('\n') print('中序遍历:') midTraverse(root) print('\n') print('后序遍历:') afterTraverse(root) print('\n')
前序遍历: DBACEGF 中序遍历: ABCDEFG 后序遍历: ACBFGED
最后,来个小题感受一下~经典的已知前序遍历结果和中序遍历结果,求后序遍历,代码如下:
preList=list('DBACEGF') midList=list('ABCDEFG') afterList=[] def findTree(preList,midList,afterList): if len(preList)==0: return if len(preList)==1: afterList.append(preList[0]) return root=preList[0] n=midList.index(root) findTree(preList[1:n+1],midList[:n],afterList) findTree(preList[n+1:],midList[n+1:],afterList) afterList.append(root) findTree(preList,midList,afterList) print(afterList)
['A', 'C', 'B', 'F', 'G', 'E', 'D']
可以看到,验证成功~
转载请注明:转自 http://blog.csdn.net/littlethunder/article/details/9707669