python16_day35【算法】

一、BTree

 1 class BinTreeNode:
 2     def __init__(self, data):
 3         self.data = data
 4         self.lchild = None
 5         self.rchild = None
 6 
 7 
 8 k = BinTreeNode('K')
 9 g = BinTreeNode('G')
10 c = BinTreeNode('C')
11 a = BinTreeNode('A')
12 b = BinTreeNode('B')
13 d = BinTreeNode('D')
14 e = BinTreeNode('E')
15 f = BinTreeNode('F')
16 h = BinTreeNode('H')
17 
18 
19 root = a
20 a.lchild = b
21 a.rchild = e
22 b.lchild = h
23 b.rchild = f
24 f.lchild = d
25 e.rchild = c
26 c.lchild = k
27 c.rchild = g
28 
29 #前序遍历 中序遍历 后序遍历
30 
31 def PreBianli(root):
32     p = root
33     if p:
34         print(p.data, end=' ')
35         PreBianli(p.lchild)
36         PreBianli(p.rchild)
37 
38 
39 def MidBianli(root):
40     p = root
41     if p:
42         MidBianli(p.lchild)
43         print(p.data, end=' ')
44         MidBianli(p.rchild)
45 
46 
47 def PostBianli(root):
48     p = root
49     if p:
50         PostBianli(p.lchild)
51         PostBianli(p.rchild)
52         print(p.data, end=' ')
53 
54 
55 def LevelBianli(root):
56     curLevel = [root]
57     nextLevel = []
58     while len(curLevel)>0:
59         for node in curLevel:
60             print(node.data, end=' ')
61             if node.lchild:
62                 nextLevel.append(node.lchild)
63             if node.rchild:
64                 nextLevel.append(node.rchild)
65         curLevel = nextLevel
66         nextLevel = []
67 
68 
69 # PreBianli(root)
70 # print()
71 # MidBianli(root)
72 # print()
73 # PostBianli(root)
74 LevelBianli(root)
View Code

 

posted @ 2017-09-23 09:28  willianflasky  阅读(137)  评论(0编辑  收藏  举报