python实现二叉排序树
作者:咕嘟咕嘟_? 时间:2022-08-26 04:34:37
方法一(粗暴)
#二叉排序树
class BTree():
def __init__(self,data):
self.left = None
self.right = None
if type(data) == list:
self.data = data[0]
for d in data[1:]:
self.insert(d)
else:
self.data = data
def insert(self,data):
bt = self
while True:
if data <= bt.data:
if bt.left == None:
bt.left = BTree(data)
break
else:
bt = bt.left
else:
if bt.right == None:
bt.right = BTree(data)
break
else:
bt = bt.right
def mid_order(self):
res = []
stack = []
node = self
while node or stack:
while node:
stack.append(node)
node = node.left
node = stack.pop()
res.append(node.data)
node = node.right
return res
data = [5,1,2,3,6,8,9]
bt = BTree(data)
print(bt.mid_order())
方法二(递归)
class TreeNode(object):
def __init__(self,data):
self.data = data
self.left = None
self.right = None
class BinaryTree(object):
def insert(self,root, node):
if root is None:
return node
if node.data < root.data:
root.left = self.insert(root.left, node)
else:
root.right = self.insert(root.right, node)
return root
def mid_order(self,root):
node = root
stack = []
res = []
while node or stack:
while node:
stack.append(node)
node = node.left
node = stack.pop()
res.append(node.data)
node = node.right
return res
data = [5,1,2,3,6,8,9]
root = TreeNode(data[0])
tree = BinaryTree()
for i in data[1:]:
tree.insert(root,TreeNode(i))
print(tree.mid_order(root))
来源:https://blog.csdn.net/EMIvv/article/details/122457325
标签:python,二叉,排序树
0
投稿
猜你喜欢
Sql Server里删除数据表中重复记录的例子
2024-01-19 18:37:31
微软补丁KB967723造成MySQL频繁无法连接
2009-11-03 14:28:00
python Pandas 读取txt表格的实例
2023-12-05 01:23:48
PHP同时连接多个mysql数据库示例代码
2023-11-23 21:12:28
Python输出PowerPoint(ppt)文件中全部文字信息的方法
2023-09-11 15:37:55
基于Python实现西西成语接龙小助手
2023-04-02 22:12:04
videocapture库制作python视频高速传输程序
2023-08-22 14:47:48
python进度条库tqdm的基本操作方法
2021-03-02 08:31:22
go语言里包的用法实例
2024-02-02 10:24:33
Python用threading实现多线程详解
2021-06-19 13:35:48
Python StringIO及BytesIO包使用方法解析
2022-12-24 15:34:26
Python中的流程控制详解
2023-07-22 20:31:54
javascript 跳转代码集合
2024-04-19 10:42:40
几个小技巧帮你实现Golang永久阻塞
2024-02-14 10:37:29
mint-ui在vue中的使用示例
2023-07-02 16:52:17
JavaScript 组件之旅(一):分析和设计
2009-09-21 10:52:00
SQL Server高级内容之子查询和表链接概述及使用
2024-01-24 22:34:27
浅谈python 中的 type(), dtype(), astype()的区别
2022-09-13 22:40:39
python实现XML解析的方法解析
2021-08-20 01:58:58
NopCommerce架构分析之(八)多语言支持
2024-05-13 09:15:53