Python_二叉树

时间:2022-04-20 14:26:28

BinaryTree.py

 '''二叉树:是每个节点最多有两个子树(分别称为左子树和右子树)的树结构,二叉树的第i层最多有2**(i-1)个节点,常用于排序或查找'''
class BinaryTree:
def __init__(self,value):
self.__left = None
self.__right = None
self.__data = value #析构函数
def __del__(self):
del self.__data #创建左子树
def insertLeftChild(self,value):
if self.__left:
print('Left child tree already exists.')
else:
self.__left = BinaryTree(value)
return self.__left #创建右子树
def insertRightChild(self,value):
if self.__right:
print('Right child tree already exits.')
else:
self.__right = BinaryTree(value)
return self.__right def show(self):
print(self.__data) #前序遍历
def preOrder(self):
print(self.__data) #输出根节点的值
if self.__left:
self.__left.preOrder() #遍历左子树
if self.__right:
self.__right.preOrder() #遍历右子树 def postOrder(self):
if self.__left:
self.__left.postOrder()
if self.__right:
self.__right.postOrder()
print(self.__data) def inOrder(self): #中序遍历
if self.__left:
self.__left.inOrder()
print(self.__data)
if self.__right:
self.__right.inOrder() if __name__ == '__main__':
print('Please use me a module')

useBinaryTree.py

 from BinaryTree import BinaryTree
root = BinaryTree('root')
b=root.insertRightChild('B')
a=root.insertLeftChild('A')
c=a.insertLeftChild('C')
d=c.insertRightChild('D')
e=b.insertRightChild('E')
f=e.insertLeftChild('F')
root.inOrder()
# C
# D
# A
# root
# B
# F
# E
root.postOrder()
# D
# C
# A
# F
# E
# B
# root
b.inOrder()
# B
# F
# E