二叉树的构建

 1 class BTree:
 2     def __init__(self, value):
 3         self.left = None            
 4         self.data = value           # 节点值
 5         self.right = None
 6 
 7     def insertLeft(self, value):    # 左子树插入节点
 8         self.left = BTree(value)
 9         return self.left
10 
11     def insertRight(self, value):   # 右子树插入节点
12         self.right = BTree(value)
13         return self.right
14 
15     def show(self):
16         print(self.data)
17 
18 if __name__ == '__main__':
19     Root = BTree('Root')
20     A = Root.insertLeft('A')
21     C = A.insertLeft('C')
22     D = A.insertRight('D')
23     F = D.insertLeft('F')
24     G = D.insertRight('G')
25     B = Root.insertRight('B')
26     E = B.insertRight('E')
27     Root.show()         # 打印根节点
28     Root.left.show()    # A
29     Root.right.show()   # B
30     A = Root.left
31     A.left.show()       # C
32     Root.left.right.show()  # D            

 

posted @ 2020-06-13 20:36  Aphelios  阅读(126)  评论(0)    收藏  举报