Python_二叉树,,BinaryTree
Python_二叉树,,BinaryTree
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.__data11 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.__left19 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.__right27 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 # C11 # D12 # A13 # root14 # B15 # F16 # E17 root.postOrder()18 # D19 # C20 # A21 # F22 # E23 # B24 # root25 b.inOrder()26 # B27 # F28 # E
Python_二叉树
相关内容
- python-进程和线程,,什么叫“多任务”呢?
- Python_字符串,,字符串:Python
- Python语音实现词频统计,,需求:1.设计一个词
- Mol Cell Proteomics. |马臻| psims-一个用于编写HUPO-PSI标准下
- python——字符串截取,,str = &lsq
- MySQL中的分页操作结合python,,mysql中的分页操
- Python3基础 hasattr 测试一个对象是否有指定的属性,,镇
- mac 在终端使用命令行启动脚本,无法使用自己安装的
- 銆怭ython銆戝瓙鍩熷悕鏌ヨ鑴氭湰,,鏍囩锛?a hre
- python3调用exe程序编写cve20190708批量检测工具,,1、pyth
评论关闭