二叉树的结构:

前中后序遍历对应的规则:

先序遍历

先序遍历的原则是:先根、再左、再右。
即:ABCDEFGH

中序遍历

中序遍历的原则是:先左、再根、再右。
即:BDCEAFHG

后序遍历

后序遍历的原则是:先左、再右、再根。
即:DECBHGFA

# 首先定义树的根节点
class Node(object):"""docstring for Node"""def __init__(self, elem=0, left=None, right=None):self.elem = elemself.lchild = leftself.rchild = right# 定义一棵二叉树
class BinaryTree(object):"""docstring for BinaryTree"""def __init__(self):# 根节点self.root = Nonedef add(self, item):# 向树中插入元素, 使用队列存储元素, 读取与弹出node = Node(item)if self.root is None:self.root = nodereturn# 用顺序表实现队列, 先入先出FIFO# 首先传入根节点信息queue = [self.root]while queue:cur_node = queue.pop(0)# 若当前节点的左孩子为空, 将节点赋给当前节点左孩子if cur_node.lchild is None:cur_node.lchild = nodereturn# 若当前节点左孩子不为空, 左孩子添加到当前节点中else:queue.append(cur_node.lchild)# 接下来同样判断右孩子if cur_node.rchild is None:cur_node.rchild = nodereturnelse:queue.append(cur_node.rchild)def breadth_travel(self):"""广度遍历: 方法同add, 是一种反过来的操作"""# 使用队列queue = [self.root]ret = []if self.root is None:returnwhile queue:cur_node = queue.pop(0)# 打印结点值# print(cur_node.elem, end=" ")ret.append(cur_node.elem)if cur_node.lchild:queue.append(cur_node.lchild)if cur_node.rchild:queue.append(cur_node.rchild)print(ret)def pre_order(self, node):"""前序遍历: 递归方法"""# if node is None:#     return# print(node.elem, end=" ")# self.pre_order(node.lchild)# self.pre_order(node.rchild)ret = []def recur_0(node):if node:ret.append(node.elem)recur_0(node.lchild)recur_0(node.rchild)recur_0(node)print(ret)def in_order(self, node):"""中序遍历"""# if node is None:#     return# self.in_order(node.lchild)# print(node.elem, end=" ")# self.in_order(node.rchild)ret = []def recur_1(node):if node:recur_1(node.lchild)ret.append(node.elem)recur_1(node.rchild)recur_1(node)print(ret)def post_order(self, node):"""后序遍历"""# 递归遍历跳出的条件# if node is None:#     return# self.pre_order(node.lchild)# self.pre_order(node.rchild)# print(node.elem, end=" ")ret = []def recur(node):if node:recur(node.lchild)recur(node.rchild)ret.append(node.elem)recur(node)print(ret)def pre_order_1(self, node):"""前序遍历(中左右): 非递归, 需要使用栈(递归的本质是栈实现)来实现"""# 定义一个栈st = []# 定义顺序数组result_arr = []if node:st.append(node)while st:node = st.pop()# 中result_arr.append(node.elem)# 右if node.rchild:st.append(node.rchild)# 左if node.lchild:st.append(node.lchild)print(result_arr)def in_order_1(self, node):"""中序遍历(左中右), 需要指针(由于遍历的节点顺序和处理的节点顺序不同)"""st = []result_arr = []cur_node = nodewhile cur_node or st:if cur_node:# 利用指针访问结点,访问到最底层数据# 结点入栈st.append(cur_node)# 左cur_node = cur_node.lchildelse:cur_node = st.pop()# 中result_arr.append(cur_node.elem)# 右cur_node = cur_node.rchildprint(result_arr)def in_order_2(self, node):"""中序遍历(左中右), 通解"""st = []result_arr = []if node:st.append(node)while st:node = st[-1]if node:st.pop()if node.rchild:st.append(node.rchild)st.append(node)# 空节点入栈作为标记st.append(None)if node.lchild:st.append(node.lchild)else:# 空节点出栈st.pop()node = st[-1]st.pop()result_arr.append(node.elem)print(result_arr)def post_order_1(self, node):"""后序遍历(左右中), 可以直接由前序遍历得到"""# 定义一个栈st = []# 定义顺序数组result_arr = []if node:st.append(node)while st:node = st.pop()# 中result_arr.append(node.elem)# 左if node.lchild:st.append(node.lchild)# 右if node.rchild:st.append(node.rchild)print(result_arr[::-1])def post_order_2(self, node):"""后序遍历(左右中), 可以直接由前序遍历得到"""# 定义一个栈st = []# 定义顺序数组result_arr = []while st or node:while node:st.append(node)# 遍历二叉树直到结点不再含有左节点(右节点)node = node.lchild if node.lchild else node.rchildnode = st.pop()# 最后加入中结点result_arr.append(node.elem)# 判断并开始遍历右节点(node指向右节点), 然后继续进行入栈操作(while内循环)node = st[-1].rchild if st and st[-1].lchild == node else Noneprint(result_arr)if __name__ == '__main__':tree = BinaryTree()for i in range(9):tree.add(i)print("广度遍历: ")tree.breadth_travel()print("\n深度遍历: ")print("前序遍历: 递归")tree.pre_order(tree.root)print("中序遍历: 递归")tree.in_order(tree.root)print("后序遍历: 递归")tree.post_order(tree.root)print()print("前序遍历: 非递归")tree.pre_order_1(tree.root)print("中序遍历: 非递归")tree.in_order_1(tree.root)print("中序遍历: 非递归, 不需要指针")tree.in_order_2(tree.root)print("后序遍历: 非递归, 修改自前序")tree.post_order_1(tree.root)print("后序遍历: 非递归, 直接写")tree.post_order_2(tree.root)"""
广度遍历:
0 1 2 3 4 5 6 7 8
深度遍历:
前序遍历: 递归
0 1 3 7 8 4 2 5 6
中序遍历: 递归
7 3 8 1 4 0 5 2 6
后序遍历: 递归
7 8 3 4 1 5 6 2 0
前序遍历: 非递归
[0, 1, 3, 7, 8, 4, 2, 5, 6]
中序遍历: 非递归
[7, 3, 8, 1, 4, 0, 5, 2, 6]
后序遍历: 非递归
[7, 8, 3, 4, 1, 5, 6, 2, 0]
"""

Python实现二叉树的前中后序遍历相关推荐

  1. 二叉树的前,中,后序遍历(思路分析) [Java][数据结构]

    二叉树的前,中,后序遍历(思路分析) 前序遍历: 先输出父节点, 再遍历左子树和右子树 中序遍历: 先遍历左子树, 再输出父节点,再遍历右子树 后序遍历: 先遍历左子树,再遍历右子树,最后输出父节点 ...

  2. Java二叉树的前中后序遍历

    Java二叉树的前中后序遍历 1.前序遍历 1.1前序遍历概念 1.2前序遍历习题 2.中序遍历 2.1中序遍历概念 2.2中序遍历习题 3.后续遍历 3.1后序遍历概念 3.2后序遍历习题 大家好, ...

  3. 数据结构之二叉树的前中后序遍历以及层序遍历

    学习目标:读完这篇博客搞定二叉树的前中后序以及层序遍历 首先:你应该明白什么是二叉树,下面这幅图就是一个完全二叉树 其实所谓的二叉树就是一个节点有小于等于二个分支的树,可以没有分支,可以有1条分支,可 ...

  4. 数据结构与算法(java):树-二叉树(二叉查找树(BST)、线索化二叉树、哈夫曼树、平衡二叉树【AVL】、二叉树的前中后序遍历)

    二叉树 1.定义 二叉树 就是度不超过2的树(每个结点最多只有两个子结点).如图 2.特殊二叉树 满二叉树 当二叉树的每一个层的结点树都达到最大值,则这个二叉树就是满二叉树. 完全二叉树 叶结点只能出 ...

  5. 二叉树的前中后序遍历之迭代法(非统一风格迭代方式)

    文章目录 前言 一.前序遍历(迭代法) 二.中序遍历(迭代法) 三.后序遍历(迭代法) 总结 前言 「递归的实现就是:每一次递归调用都会把函数的局部变量.参数值和返回地址等压入调用栈中」,然后递归返回 ...

  6. 二叉树的前中后序遍历(考试常考)

    二叉树遍历的概念 二叉树的遍历是按某种规则对二叉树的每个节点均只被访问一次,根据根节点访问位置的不同分为三种:先序遍历(根左右).中序遍历(左根右).后序遍历(左右根).         由于树是通过 ...

  7. 【数据结构】二叉树的前中后序遍历

    二叉树的三种遍历 1. 创建一棵简单的二叉树 1.1 二叉树结构体实现 1.2 创造一个二叉树结点的函数 1.3 手动创造一棵二叉树 2.为什么要遍历? 3.最重要的知识:由二叉树引出的子问题分析 4 ...

  8. 二叉树的前中后序遍历之迭代法(统一风格迭代方式)

    一.前序遍历(迭代法)->右左中 前序遍历是中左右,每次先处理的是中间节点,那么先将根节点放入栈中,然后将右孩子加入栈,再加入左孩子. 为什么要先加入 右孩子,再加入左孩子呢?因为这样出栈的时候 ...

  9. (必背)二叉树的前中后序遍历(利用栈)

    二叉树的前序遍历(利用栈) 1.首先将根节点压入栈 2.栈中的首元素出栈,然后先将其右节点压入栈中,再将栈中的左节点压入栈中(如果左右节点分别存在的话) 3.重复步骤2直到栈为空 class Solu ...

  10. 二叉树的前中后序遍历(栈)(C++)

    二叉树的遍历是很基础的东西,用递归是很简洁明了的写法,但是栈的写法也可以了解一下 #include<vector> #include<stack> struct TreeNod ...

最新文章

  1. java调用系统时间函数_JAVA自学笔记:不使用系统函数来计算日期处于当年的第多少天...
  2. vb inet 一些方法
  3. 关于指针和链表中的一些问题
  4. python excel整合_如何整合100张excel表到一张excel表
  5. 如何插入8bit量化节点(tensorflow)
  6. 微信小程序登录 更新中
  7. 上传 jar 包到 nexus3、上传本地 jar 包到 maven 私服
  8. appweb ejs_EJS部分
  9. .net mysql操作类_ASP.NET数据库操作类实例
  10. 飞狐的日线 java_JAVA 版 ATX-Client
  11. levy过程、扩散过程、随机过程带跳
  12. 图标缩排和悬浮突显的简单实现
  13. 什么是 1号信令、7号信令和PRI信令?
  14. 有趣的微分方程传之可分离变量的微分方程
  15. 7.25~7.26 周末翻倍奖励——滴滴快车单
  16. 关于options请求的一点理解
  17. Tomcat 降权操作
  18. playsound 模块解决 UnicodeDecodeError 异常
  19. Android ADB工具-管理设备/取设备硬件信息(一)
  20. [解决办法] Caused by: java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0

热门文章

  1. QCC Practice
  2. 什么是数据库?以及主流的数据库有哪些
  3. usb转rs485测试软件,usb转rs485
  4. brctl: command not found
  5. yum install brctl报错
  6. FreeImage的学习总结总结(一)
  7. 威联通建php邮件服务器_威联通 ※ 群晖 虚拟机性能对比 我可能要碰瓷 eSir
  8. 一项千年太空任务即将拯救人类——科学家们正在密谋中
  9. 谷歌浏览器插件离线安装
  10. 【深度学习】基于PyTorch搭建ResNet18、ResNet34、ResNet50、ResNet101、ResNet152网络