Python—二叉树数据结构
2024-10-08 14:37:17
二叉树
简介:
二叉树是每个结点最多有两个子树的树结构。通常子树被称作“左子树”(left subtree)和“右子树”(right subtree)。
二叉树二叉树的链式存储:
将二叉树的节点定义为一个对象,节点之间通过类似链表的链接方式来连接。
节点定义:
二叉树的遍历:
二叉树的遍历方式:
前序遍历:EACBDGF
中序遍历:ABCDEGF
后序遍历:BDCAFGE
层次遍历:EAGCFBD
代码实现:
# _*_ coding=utf-8 _*_ """
实现一个二叉树结果,并进行遍历
E
/ \
A G
\ \
C F
/ \
B D
"""
from collections import deque class BinaryTree(object):
def __init__(self, data):
self.data = data
self.child_l = None
self.child_r = None # 创建
a = BinaryTree("A")
b = BinaryTree("B")
c = BinaryTree("C")
d = BinaryTree("D")
e = BinaryTree("E")
f = BinaryTree("F")
g = BinaryTree("G") # 构造节点关系
e.child_l = a
e.child_r = g
a.child_r = c
c.child_l = b
c.child_r = d
g.child_r = f # 设置根
root = e def pre_order(tree):
"""
前序遍历:root -> child_l -> child_r
:param tree: the root of tree
:return:
"""
if tree:
print(tree.data, end=',')
# print("")
pre_order(tree.child_l)
pre_order(tree.child_r) def in_order(tree):
"""
中序遍历:child_l -> root -> child_r
:param tree:
:return:
"""
if tree:
in_order(tree.child_l)
print(tree.data, end=',')
in_order(tree.child_r) def post_order(tree):
"""
后序遍历:child_l -> child_r -> root
:param tree:
:return:
"""
if tree:
post_order(tree.child_l)
post_order(tree.child_r)
print(tree.data, end=',') def level_order(tree):
"""
层次遍历:E -> AG -> CF -> BD
使用队列实现
:param tree:
:return:
"""
queue = deque()
queue.append(tree) # 先把根添加到队列
while len(queue): # 队列不为空
node = queue.popleft()
print(node.data, end=',')
if node.child_l:
queue.append(node.child_l)
if node.child_r:
queue.append(node.child_r) pre_order(root)
print('')
in_order(root)
print('')
post_order(root)
print('')
level_order(root)
最新文章
- shell脚本变量
- Scalding初探之三:Hadoop实战
- 关于Java的数据结构HashMap,ArrayList的使用总结及使用场景和原理分析
- SparkSQL使用之Thrift JDBC server
- 学习CentOS7笔记(一)
- Mac下安装HBase及详解
- 初次接触pyqt
- Objective-C 学习笔记(Day 2)
- CH Round #53 -【Nescafé 32】杯NOIP模拟赛
- matlab画甘特图
- jstree使用小结(三)
- linux系统下phpstudy里的mysql使用方法
- SmartSql Config配置
- 2018-2019 20165221 网络对抗 Exp5 MSF基础
- 解决win系统无法安装.NET Framework 4.0 4.6 原因是HRESULT0xc8000222
- java中的缓冲流!
- 多项式乘法(FFT)学习笔记
- 【SVN】CentOS7.0下搭建SVN服务器
- GitHub linux 提交文件及403错误处理
- jvm虚拟机--垃圾回收子系统