递归/非递归----python深度遍历二叉树(前序遍历,中序遍历,后序遍历)

递归代码:递归实现很简单

 1 '二叉树结点类'
 2 class TreeNode:
 3     def __init__(self, x):
 4         self.val = x
 5         self.left = None
 6         self.right = None
 7         
 8 '列表创建二叉树'
 9 def listcreattree(root,llist,i):###用列表递归创建二叉树,
10     #它其实创建过程也是从根开始a开始,创左子树b,再创b的左子树,如果b的左子树为空,返回none。
11     #再接着创建b的右子树,
12     if i<len(llist):
13         if llist[i] =='#':
14             return None ###这里的return很重要
15         else:
16             root=TreeNode(llist[i])
18             #往左递推
19             root.left=listcreattree(root.left,llist,2*i+1)#从根开始一直到最左,直至为空,
20             #往右回溯
21             root.right=listcreattree(root.right, llist,2*i+2)#再返回上一个根,回溯右,
22             #回溯到最原始的根,再返回'
24             return root  ###这里的return很重要
25     return root
26 #测试
27 llist=[5,4,3,'#','#',1,2]
28 root = listcreattree(None,llist,0)        
29 
30 
31 
32 '深度优先遍历二叉树'
33 '''  /**
34      * 深度优先遍历,相当于先根遍历
35      * 采用非递归实现
36      * 需要辅助数据结构:栈
37      */'''
38 
39 #前序遍历
40 def preoder(t):
41     if t == None:
42         return 
43     print(t.val)
44     preoder(t.left)
45     preoder(t.right)
46 #测试
47 print('前序遍历:')
48 preoder(root)
49 
50 #中序遍历
51 def binoder(t):
52     if t:
53         binoder(t.left)
54         print(t.val)
55         binoder(t.right)  
56 #测试
57 print('中序遍历:')
58 binoder(root)
59 
60 
61 #后序遍历
62 def pastoder(t):
63     if t:
64         pastoder(t.left)
65         pastoder(t.right)
66         print(t.val)   
67 #测试
68 print('后序遍历:')
69 pastoder(root)

二叉树图:

运行结果:

 1 前序遍历:
 2 5
 3 4
 4 3
 5 1
 6 2
 7 中序遍历:
 8 4
 9 5
10 1
11 3
12 2
13 后序遍历:
14 4
15 1
16 2
17 3
18 5

非递归实现:以前序遍历为例,基本思想为

(1)由于采取前序遍历,遇到节点就应该访问,下一步应该沿着树的左分支下行。

(2)但节点的右分支(右子树)还没有访问,因此需要记录,将右子结点入栈。

(3)遇到空树时回溯,取出栈中保存的一个右分支,像一棵二叉树一样去遍历它。

posted @ 2018-03-15 16:58  baibaibaiyou  阅读(519)  评论(1编辑  收藏  举报