首页 > 代码库 > Python_二叉树

Python_二叉树

BinaryTree.py

 1 ‘‘‘二叉树:是每个节点最多有两个子树(分别称为左子树和右子树)的树结构,二叉树的第i层最多有2**(i-1)个节点,常用于排序或查找‘‘‘
 2 class BinaryTree:
 3     def __init__(self,value):
 4         self.__left = None
 5         self.__right = None
 6         self.__data = value
 7 
 8     #析构函数
 9     def __del__(self):
10         del self.__data
11 
12     #创建左子树
13     def insertLeftChild(self,value):
14         if self.__left:
15             print(Left child tree already exists.)
16         else:
17             self.__left = BinaryTree(value)
18             return self.__left
19 
20     #创建右子树
21     def insertRightChild(self,value):
22         if self.__right:
23             print(Right child tree already exits.)
24         else:
25             self.__right = BinaryTree(value)
26             return self.__right
27 
28     def show(self):
29         print(self.__data)
30 
31     #前序遍历
32     def preOrder(self):
33         print(self.__data)  #输出根节点的值
34         if self.__left:
35             self.__left.preOrder()  #遍历左子树
36         if self.__right:
37             self.__right.preOrder() #遍历右子树
38 
39     def postOrder(self):
40         if self.__left:
41             self.__left.postOrder()
42         if self.__right:
43             self.__right.postOrder()
44         print(self.__data)
45 
46     def inOrder(self):  #中序遍历
47         if self.__left:
48             self.__left.inOrder()
49         print(self.__data)
50         if self.__right:
51             self.__right.inOrder()
52 
53 if __name__ == __main__:
54     print(Please use me a module)

useBinaryTree.py

 1 from BinaryTree import BinaryTree
 2 root = BinaryTree(root)
 3 b=root.insertRightChild(B)
 4 a=root.insertLeftChild(A)
 5 c=a.insertLeftChild(C)
 6 d=c.insertRightChild(D)
 7 e=b.insertRightChild(E)
 8 f=e.insertLeftChild(F)
 9 root.inOrder()
10 # C
11 # D
12 # A
13 # root
14 # B
15 # F
16 # E
17 root.postOrder()
18 # D
19 # C
20 # A
21 # F
22 # E
23 # B
24 # root
25 b.inOrder()
26 # B
27 # F
28 # E

 

Python_二叉树