教你如何使用Python实现二叉树结构及三种遍历


Posted in Python onJune 18, 2021

一:代码实现

class TreeNode:
    """节点类"""
    def __init__(self, mid, left=None, right=None):
        self.mid = mid
        self.left = left
        self.right = right


# 树类
class Tree:
    """树类"""
    def __init__(self, root=None):
        self.root = root

    def add(self, item):
        # 将要添加的数据封装成一个node结点
        node = TreeNode(item)
        if not self.root:
            self.root = node
            return
        queue = [self.root]
        while queue:
            cur = queue.pop(0)
            if not cur.left:
                cur.left = node
                return
            else:
                queue.append(cur.left)

            if not cur.right:
                cur.right = node
                return
            else:
                queue.append(cur.right)
               
tree = Tree()
tree.add(0)
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
tree.add(6)

二:遍历

在上述树类代码基础上加遍历函数,基于递归实现。

教你如何使用Python实现二叉树结构及三种遍历

先序遍历:

先序遍历结果是:0 -> 1 -> 3 -> 4 -> 2 -> 5 -> 6

# 先序遍历
    def preorder(self, root, result=[]):
        if not root:
            return
        result.append(root.mid)
        self.preorder(root.left, result)
        self.preorder(root.right, result)
        return result
        
print("先序遍历")
print(tree.preorder(tree.root))
"""
先序遍历
[0, 1, 3, 4, 2, 5, 6]
"""

中序遍历:

中序遍历结果是:3 -> 1 -> 4 -> 0 -> 5 -> 2 -> 6

# 中序遍历
    def inorder(self, root, result=[]):
        if not root:
            return result
        self.inorder(root.left, result)
        result.append(root.mid)
        self.inorder(root.right, result)
        return result
        
print("中序遍历")
print(tree.inorder(tree.root))
"""
中序遍历
3, 1, 4, 0, 5, 2, 6]
"""

后续遍历

后序遍历结果是:3 -> 4 -> 1 -> 5 -> 6 -> 2 -> 0

# 后序遍历
    def postorder(self, root, result=[]):
        if not root:
            return result
        self.postorder(root.left, result)
        self.postorder(root.right, result)
        result.append(root.mid)

        return result
        
print("后序遍历")
print(tree.postorder(tree.root))
"""
后序遍历
[3, 4, 1, 5, 6, 2, 0]
"""

到此这篇关于教你如何使用Python实现二叉树结构及三种遍历的文章就介绍到这了,更多相关Python实现二叉树结构及三种遍历内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python中几种操作字符串的方法的介绍
Apr 09 Python
WINDOWS 同时安装 python2 python3 后 pip 错误的解决方法
Mar 16 Python
Python3 socket同步通信简单示例
Jun 07 Python
Python实现扩展内置类型的方法分析
Oct 16 Python
python爬虫使用cookie登录详解
Dec 27 Python
一篇文章快速了解Python的GIL
Jan 12 Python
python清除字符串中间空格的实例讲解
May 11 Python
pandas将多个dataframe以多个sheet的形式保存到一个excel文件中
Oct 10 Python
pytorch 常用线性函数详解
Jan 15 Python
python实现用类读取文件数据并计算矩形面积
Jan 18 Python
Python2和Python3中@abstractmethod使用方法
Feb 04 Python
详解selenium + chromedriver 被反爬的解决方法
Oct 28 Python
Python实现智慧校园自动评教全新版
python用海龟绘图写贪吃蛇游戏
Python使用海龟绘图实现贪吃蛇游戏
Jun 18 #Python
Python turtle实现贪吃蛇游戏
python中%格式表达式实例用法
Jun 18 #Python
如何用python清洗文件中的数据
Jun 18 #Python
Python中glob库实现文件名的匹配
You might like
什么是短波收听SWL
2021/03/01 无线电
PHP面向对象学习笔记之一 基础概念
2012/10/06 PHP
PHP中fwrite与file_put_contents性能测试代码
2013/08/02 PHP
CI框架开发新浪微博登录接口源码完整版
2014/05/28 PHP
ThinkPHP提交表单时默认自动转义的解决方法
2014/11/25 PHP
详谈PHP中public,private,protected,abstract等关键字的用法
2017/12/31 PHP
jQuery实现页面滚动时层智能浮动定位实例探讨
2013/03/29 Javascript
轻松理解vue的双向数据绑定问题
2017/10/30 Javascript
浅谈vue项目打包优化策略
2018/09/29 Javascript
JavaScript前端实现压缩图片功能
2020/03/06 Javascript
vue 修改 data 数据问题并实时显示操作
2020/09/07 Javascript
[46:47]2014 DOTA2国际邀请赛中国区预选赛 DT VS HGT
2014/05/22 DOTA
[55:56]NB vs Infamous 2019国际邀请赛淘汰赛 败者组 BO3 第二场 8.22
2019/09/05 DOTA
让Python代码更快运行的5种方法
2015/06/21 Python
Python实现约瑟夫环问题的方法
2016/05/03 Python
详解python之协程gevent模块
2018/06/14 Python
python pandas实现excel转为html格式的方法
2018/10/23 Python
python实现石头剪刀布程序
2021/01/20 Python
python requests模拟登陆github的实现方法
2019/12/26 Python
Python面向对象封装操作案例详解
2019/12/31 Python
python GUI计算器的实现
2020/10/09 Python
快速创建python 虚拟环境
2020/11/28 Python
解决virtualenv -p python3 venv报错的问题
2021/02/05 Python
详解HTML5中div和section以及article的区别
2015/07/14 HTML / CSS
老海军美国官网:Old Navy
2016/09/05 全球购物
自荐书模板
2013/12/19 职场文书
《梅兰芳学艺》教学反思
2014/02/24 职场文书
2014小学植树节活动总结
2014/03/10 职场文书
软件售后服务承诺书
2014/05/21 职场文书
节约能源标语
2014/06/17 职场文书
商场租赁意向书
2014/07/30 职场文书
市场策划求职信
2014/08/07 职场文书
群众路线教育实践活动思想汇报(2014特荐篇)
2014/09/16 职场文书
小学中等生评语
2014/12/29 职场文书
新党员入党决心书
2015/09/22 职场文书
webpack介绍使用配置教程详解webpack介绍和使用
2022/06/25 Javascript