1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # @Date : 2016-11-18 08:53:45 4 # @Author : why_not_try 5 # @Link : http://example.org 6 # @Version : python 2.7 7 8 class Tree(object): 9 def __init__(self,data,left,right): 10 self.data=data 11 self.left=left 12 self.right=right 13 def post_visit(Tree): 14 if Tree: 15 post_visit(Tree.left) 16 post_visit(Tree.right) 17 print Tree.data 18 def pre_visit(Tree): 19 if Tree: 20 print Tree.data 21 pre_visit(Tree.left) 22 pre_visit(Tree.right) 23 def in_visit(Tree): 24 if Tree: 25 in_visit(Tree.left) 26 print Tree.data 27 in_visit(Tree.right) 28 node1=Tree(1,0,0) 29 node2=Tree(2,0,0) 30 node3=Tree(3,node1,node2) 31 node4=Tree(4,0,0) 32 node5=Tree(5,node4,node3) 33 34 print "the post_visit is ....." 35 post_visit(node5) 36 37 print "the pre_visit is......." 38 pre_visit(node5) 39 40 print "the in_visit is ......." 41 in_visit(node5)
代码很简单,相信一看大部分就能理解。在每一个遍历算法中首先if Tree 为了防止树的左节点或右节点为空时(0代表为空)还去遍历 ,此时程序运行将会报错。
此为node5:
运行结果如下: