python二叉樹遞歸算法之后序遍歷,前序遍歷,中序遍歷


 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:

 

運行結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM