博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
数据结构(python) —— 【26: 二叉树及其操作】
阅读量:3943 次
发布时间:2019-05-24

本文共 1988 字,大约阅读时间需要 6 分钟。

二叉树

树是一种数据结构 比如:目录结构

树是一种可以递归定义的数据结构
树是由n个节点组成的集合:

  • 如果n=0,那这是一棵空树;
  • 如果n>0,那存在1个节点作为树的根节点,其他节点可以分为m个集合,每个集合本身又是一棵树。

二叉树的基本概念可以看我前面的博客:

二叉树的链式存储: 将二叉树的节点定义为一个对象,节点之间通过类似链表的链接方式来连接。

二叉树的遍历:
二叉树的遍历简单用代码对二叉树实现一下:

'''TOPIC: 二叉树的概念(节点的建立)author: Bluetime: 2020-08-16QQ: 2458682080'''class BiTreeNode:    def __init__(self, data):        self.data = data        self.lchild = None   # 左孩子        self.rchild = None   # 右孩子a = BiTreeNode("A")b = BiTreeNode("B")c = BiTreeNode("C")d = BiTreeNode("D")e = BiTreeNode("E")f = BiTreeNode("F")g = BiTreeNode("G")e.lchild = ae.rchild = ga.rchild = cc.lchild = bc.rchild = dg.rchild = froot = e

二叉树的遍历:

'''TOPIC: 二叉树的遍历author: Bluetime: 2020-08-16QQ: 2458682080'''from collections import dequeclass BiTreeNode:    def __init__(self, data):        self.data = data        self.lchild = None   # 左孩子        self.rchild = None   # 右孩子a = BiTreeNode("A")b = BiTreeNode("B")c = BiTreeNode("C")d = BiTreeNode("D")e = BiTreeNode("E")f = BiTreeNode("F")g = BiTreeNode("G")e.lchild = ae.rchild = ga.rchild = cc.lchild = bc.rchild = dg.rchild = froot = e# print(root.lchild.rchild.data)# 前序遍历(先递归左子树,再递归右子树)def pre_order(root):    if root:        print(root.data, end=",")        pre_order(root.lchild)        pre_order(root.rchild)pre_order(root)print('\n')# 中序遍历(先递归左子树,再访问自己,再递归右子树)def in_order(root):    if root:        in_order(root.lchild)        print(root.data, end=",")        in_order(root.rchild)in_order(root)print('\n')# 后续遍历(先递归左,后递归有,最后打印自己)def post_order(root):    if root:        post_order(root.lchild)        post_order(root.rchild)        print(root.data, end=",")post_order(root)print('\n')# 层次遍历def level_order(root):    queue = deque()    queue.append(root)    while len(queue) > 0:  # 只要队不空        node = queue.popleft()  # 要进队,先出队一个        print(node.data, end=",")        if node.lchild:   # 出队的这个有没有左孩子,有的话,进队            queue.append(node.lchild)        if node.rchild:   # 出队的这个有没有右孩子,有的话,进队            queue.append(node.rchild)level_order(root)

转载地址:http://pbiwi.baihongyu.com/

你可能感兴趣的文章
word文档不能显示图片的处理
查看>>
linux的多桌面环境Xephyr
查看>>
初探debian桌面的管理启动
查看>>
七层协议图
查看>>
华为交换机作为AC的条件
查看>>
禁用Ubuntu 15.04登录界面显示客人会话(简单-实用)
查看>>
linux X下安装的软件
查看>>
Linux监测某一时刻对外的IP连接情况
查看>>
CentOS7 最小环境安装Jumpserver 1.0版脚本
查看>>
X-Security X的安全控制
查看>>
openVAS的安装
查看>>
Centos 6.5 初始安装无网卡驱动解决方法
查看>>
linux中的网桥bridge
查看>>
linux中的teaming与bonding
查看>>
LVM
查看>>
用shell切分文件--split
查看>>
python中判断字符是否为中文
查看>>
Python - 利用zip函数将两个列表(list)组成字典(dict)
查看>>
python-全角转半角
查看>>
Python pass语句作用与用法
查看>>