python数据结构之二叉树的遍历实例
遍历方案
从二叉树的递归定义可知,一棵非空的二叉树由根结点及左、右子树这三个基本部分组成。因此,在任一给定结点上,可以按某种次序执行三个操作:
1).访问结点本身(N)
2).遍历该结点的左子树(L)
3).遍历该结点的右子树(R)
有次序:
NLR、LNR、LRN
遍历的命名
根据访问结点操作发生位置命名:
NLR:前序遍历(PreorderTraversal亦称(先序遍历)) ——访问结点的操作发生在遍历其左右子树之前。
LNR:中序遍历(InorderTraversal) ——访问结点的操作发生在遍历其左右子树之中(间)。
LRN:后序遍历(PostorderTraversal) ——访问结点的操作发生在遍历其左右子树之后。
注:由于被访问的结点必是某子树的根,所以N(Node)、L(Left subtlee)和R(Right subtree)又可解释为根、根的左子树和根的右子树。NLR、LNR和LRN分别又称为先根遍历、中根遍历和后根遍历。
遍历算法
1).先序遍历的递归算法定义:
若二叉树非空,则依次执行如下操作:
a.访问根结点
b.遍历左子树
c.遍历右子树
2).中序遍历的递归算法定义:
若二叉树非空,则依次执行如下操作:
a.遍历左子树
b.访问根结点
c.遍历右子树
3).后序遍历得递归算法定义:
若二叉树非空,则依次执行如下操作:
a.遍历左子树
b.遍历右子树
c.访问根结点
一、二叉树的递归遍历:
# -*- coding: utf - 8 - *-
class TreeNode(object): def __init__(self, left=0, right=0, data=0):
self.left = left
self.right = right
self.data = data class BTree(object): def __init__(self, root=0):
self.root = root def is_empty(self):
if self.root is 0:
return True
else:
return False def preorder(self, treenode):
'前序(pre-order,NLR)遍历'
if treenode is 0:
return
print(treenode.data)
self.preorder(treenode.left)
self.preorder(treenode.right) def inorder(self, treenode):
'中序(in-order,LNR'
if treenode is 0:
return
self.inorder(treenode.left)
print(treenode.data)
self.inorder(treenode.right) def postorder(self, treenode):
'后序(post-order,LRN)遍历'
if treenode is 0:
return
self.postorder(treenode.left)
self.postorder(treenode.right)
print(treenode.data) node1 = TreeNode(data=1)
node2 = TreeNode(node1, 0, 2)
node3 = TreeNode(data=3)
node4 = TreeNode(data=4)
node5 = TreeNode(node3, node4, 5)
node6 = TreeNode(node2, node5, 6)
node7 = TreeNode(node6, 0, 7)
node8 = TreeNode(data=8)
root = TreeNode(node7, node8, 'root') bt = BTree(root) print(u''' #生成的二叉树 # ------------------------
# root
# 7 8
# 6
# 2 5
# 1 3 4
#
# ------------------------- ''')
print('前序(pre-order,NLR)遍历 :\n')
bt.preorder(bt.root) print('中序(in-order,LNR) 遍历 :\n')
bt.inorder(bt.root) print('后序(post-order,LRN)遍历 :\n')
bt.postorder(bt.root)
输出:
#生成的二叉树 # ------------------------
# root
# 7 8
# 6
# 2 5
# 1 3 4
#
# ------------------------- 前序(pre-order,NLR)遍历 : root
7
6
2
1
5
3
4
8
中序(in-order,LNR) 遍历 : 1
2
6
3
5
4
7
root
8
后序(post-order,LRN)遍历 : 1
2
3
4
5
6
7
8
root
二、.二叉树的非递归遍历
下面就用非递归的方式实现一遍。主要用到了 stack 和 queue维护一些数据节点:
# -*- coding: utf - 8 - *-
class TreeNode(object): def __init__(self, left=0, right=0, data=0):
self.left = left
self.right = right
self.data = data class BTree(object): def __init__(self, root=0):
self.root = root def is_empty(self):
if self.root is 0:
return True
else:
return False def preorder(self, treenode):
'前序(pre-order,NLR)遍历'
stack = []
while treenode or stack:
if treenode is not 0:
print(treenode.data)
stack.append(treenode)
treenode = treenode.left
else:
treenode = stack.pop()
treenode = treenode.right def inorder(self, treenode):
'中序(in-order,LNR) 遍历'
stack = []
while treenode or stack:
if treenode:
stack.append(treenode)
treenode = treenode.left
else:
treenode = stack.pop()
print(treenode.data)
treenode = treenode.right # def postorder(self, treenode):
# stack = []
# pre = 0
# while treenode or stack:
# if treenode:
# stack.append(treenode)
# treenode = treenode.left
# elif stack[-1].right != pre:
# treenode = stack[-1].right
# pre = 0
# else:
# pre = stack.pop()
# print pre.data def postorder(self, treenode):
'后序(post-order,LRN)遍历'
stack = []
queue = []
queue.append(treenode)
while queue:
treenode = queue.pop()
if treenode.left:
queue.append(treenode.left)
if treenode.right:
queue.append(treenode.right)
stack.append(treenode)
while stack:
print(stack.pop().data) def levelorder(self, treenode):
from collections import deque
if not treenode:
return
q = deque([treenode])
while q:
treenode = q.popleft()
print(treenode.data)
if treenode.left:
q.append(treenode.left)
if treenode.right:
q.append(treenode.right) node1 = TreeNode(data=1)
node2 = TreeNode(node1, 0, 2)
node3 = TreeNode(data=3)
node4 = TreeNode(data=4)
node5 = TreeNode(node3, node4, 5)
node6 = TreeNode(node2, node5, 6)
node7 = TreeNode(node6, 0, 7)
node8 = TreeNode(data=8)
root = TreeNode(node7, node8, 'root') bt = BTree(root) print(u''' #生成的二叉树 # ------------------------
# root
# 7 8
# 6
# 2 5
# 1 3 4
#
# ------------------------- ''')
print('前序(pre-order,NLR)遍历 :\n')
bt.preorder(bt.root) print('中序(in-order,LNR) 遍历 :\n')
bt.inorder(bt.root) print('后序(post-order,LRN)遍历 :\n')
bt.postorder(bt.root) print('层序(level-order,LRN)遍历 :\n')
bt.levelorder(bt.root)
输出:
#生成的二叉树 # ------------------------
# root
# 7 8
# 6
# 2 5
# 1 3 4
#
# ------------------------- 前序(pre-order,NLR)遍历 : root
7
6
2
1
5
3
4
8
中序(in-order,LNR) 遍历 : 1
2
6
3
5
4
7
root
8
后序(post-order,LRN)遍历 : 1
2
3
4
5
6
7
8
root
层序(level-order,LRN)遍历 : root
7
8
6
2
5
1
3
4
python数据结构之二叉树的遍历实例的更多相关文章
- python数据结构之二叉树的建立实例
先建立二叉树节点,有一个data数据域,left,right 两个指针域 # coding:utf-8 class TreeNode(object): def __init__(self,left=N ...
- python数据结构之二叉树的统计与转换实例
python数据结构之二叉树的统计与转换实例 这篇文章主要介绍了python数据结构之二叉树的统计与转换实例,例如统计二叉树的叶子.分支节点,以及二叉树的左右两树互换等,需要的朋友可以参考下 一.获取 ...
- 【数据结构】二叉树的遍历(前、中、后序及层次遍历)及leetcode107题python实现
文章目录 二叉树及遍历 二叉树概念 二叉树的遍历及python实现 二叉树的遍历 python实现 leetcode107题python实现 题目描述 python实现 二叉树及遍历 二叉树概念 二叉 ...
- 算法与数据结构(三) 二叉树的遍历及其线索化(Swift版)
前面两篇博客介绍了线性表的顺序存储与链式存储以及对应的操作,并且还聊了栈与队列的相关内容.本篇博客我们就继续聊数据结构的相关东西,并且所涉及的相关Demo依然使用面向对象语言Swift来表示.本篇博客 ...
- 【PHP数据结构】二叉树的遍历及逻辑操作
上篇文章我们讲了许多理论方面的知识,虽说很枯燥,但那些都是我们今天学习的前提,一会看代码的时候你就会发现这些理论知识是多么地重要了.首先,我们还是要说明一下,我们学习的主要内容是二叉树,因为二叉树是最 ...
- python数据结构之二叉树遍历的实现
本篇是实现二叉树的三种遍历,先序遍历,中序遍历,后序遍历 #!/usr/bin/python # -*- coding: utf-8 -*- class TreeNode(object): def _ ...
- Python数据结构之二叉树
本来打算一个学期分别用C++.Python.Java实现数据结构,看来要提前了 这个是Python版本,我写的数据结构尽量保持灵活性,本文bt1是一般的插入法建立二叉树结构,bt2就是可以任意输入,至 ...
- python数据结构之二叉树的实现
树的定义 树是一种重要的非线性数据结构,直观地看,它是数据元素(在树中称为结点)按分支关系组织起来的结构,很象自然界中的树那样.树结构在客观世界中广泛存在,如人类社会的族谱和各种社会组织机构都可用树形 ...
- python 数据结构之二叉树
二叉树关键在构建和遍历,python实现相对简单,我们在实现需要用到类,分别设置爱左右子树,根节点,然后从根进行遍历,进行判断,若为空进行树的构建,非空则返回到列表中即可,我在进行遍历时产生了一个错误 ...
随机推荐
- tars 问题汇总
1. 节点 ip地址变了如何解决.后台不可以改. 2. [ok] 服务如何在本地运行../HelloGo --config.conf
- 深入了解Kafka【二】工作流程及文件存储机制
1.Kafka工作流程 Kafka中的消息以Topic进行分类,生产者与消费者都是面向Topic处理数据. Topic是逻辑上的概念,而Partition是物理上的概念,每个Partition分为多个 ...
- ctf常见源码泄露
前言 在ctf中发现很多源码泄露的题,总结一下,对于网站的搭建要注意删除备份文件,和一些工具的使用如git,svn等等的规范使用,避免备份文件出现在公网 SVN源码泄露 原理 SVN(subversi ...
- leetcode刷题-57插入区间
题目 给出一个无重叠的 ,按照区间起始端点排序的区间列表. 在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间). 示例 1: 输入:intervals = ...
- roarctf_2019_easy_pwn
这篇博客主要记录当直接在malloc_hook中直接写入one_gadget不起作用时的一些处理方法.题目附件:https://buuoj.cn/challenges#roarctf_2019_eas ...
- datattable循环读取数据用于循环遍历checkboxlist里的项目
DataTable dt = bptb.GetList("Pro_ID="+id).Tables[0]; foreach (ListItem li in from DataRow ...
- 360浏览器最小字号12的坑 -彻底搞清rem
之前做响应式网站,使用rem作为单位.因为浏览器的默认字号是16px,设置html {font-size: 62.5%; /*10 ÷ 16 × 100% = 62.5%*/},刚好1rem =10p ...
- oracle之二检查点
检查点(checkpoint) 8.1 什么是checkpointcheckpoint是数据库的一个内部事件,检查点激活时会触发数据库写进程(DBWR),将数据缓冲区里的脏数据块写到数据文件中. 8. ...
- Tomcat vs Jetty vs Undertow性能对比
Tomcat,Jetty和Undertow是目前比较主流的3款Servlet容器,而且Spring Boot框架还提供了对它们的集成支持(默认使用的是Tomcat),网络上有许多文章都在介绍Under ...
- Java沙箱安全机制介绍【转载】
沙箱安全机制的应用层面:360沙箱.win10沙箱.包括VMware Workstation.Oracle VM VirtualBox都可以充当沙箱去使用,沙箱中的操作与本机无关,进而保证本机的安全性 ...