二叉树

 1 class Node(object):
 2     def __init__(self,sName):
 3         self._lChildren = []
 4         self.sName = sName
 5     def __repr__(self):
 6         return "<Node '{}'>".format(self.sName)
 7     def append(self,*args,**kwargs):
 8         self._lChildren.append(*args,**kwargs)
 9     #深度遍历
10     def print_all_1(self):
11         print(self)
12         for oChild in self._lChildren:
13             oChild.print_all_1()
14     #广度遍历
15     def print_all_2(self):
16         def gen(o):
17             lAll = [o,]
18             while lAll:
19                 oNext = lAll.pop(0)
20                 lAll.extend(oNext._lChildren)
21                 yield oNext
22         for oNode in gen(self):
23             print(oNode)
24 
25 oRoot = Node("root")
26 oChild1 = Node("child1")
27 oChild2 = Node("child2")
28 oChild3 = Node("child3")
29 oChild4 = Node("child4")
30 oChild5 = Node("child5")
31 oChild6 = Node("child6")
32 oChild7 = Node("child7")
33 oChild8 = Node("child8")
34 oChild9 = Node("child9")
35 oChild10 = Node("child10")
36 
37 #向二叉树中加入节点
38 oRoot.append(oChild1)
39 oRoot.append(oChild2)
40 oRoot.append(oChild3)
41 oChild1.append(oChild4)
42 oChild1.append(oChild5)
43 oChild2.append(oChild6)
44 oChild4.append(oChild7)
45 oChild3.append(oChild8)
46 oChild3.append(oChild9)
47 oChild6.append(oChild10)
48 #深度优先
49 oRoot.print_all_1()
50 #广度优先
51 oRoot.print_all_2()

 



posted @ 2018-02-26 09:25  隔壁古二蛋  阅读(183)  评论(0编辑  收藏  举报