Python实现二叉树及其4种遍历
Python & BinaryTree
1. BinaryTree (二叉树)
二叉树是有限个元素的集合,该集合或者为空、或者有一个称为根节点(root)的元素及两个互不相交的、分别被称为左子树和右子树的二叉树组成。
- 二叉树的每个结点至多只有二棵子树(不存在度大于2的结点),二叉树的子树有左右之分,次序不能颠倒。
- 二叉树的第i层至多有2^{i-1}个结点
- 深度为k的二叉树至多有2^k-1个结点;
- 对任何一棵二叉树T,如果其终端结点数为N0,度为2的结点数为N2,则N0=N2+1
2:二叉树遍历图解说明
前序遍历:根-左-右

中序遍历:左-根-右

后序遍历:左-右-根

3. 二叉树
- 生成二叉树
# init a tree
def InitBinaryTree(dataSource, length):
root = BTNode(dataSource[0]) for x in xrange(1,length):
node = BTNode(dataSource[x])
InsertElementBinaryTree(root, node)
return root
print 'Done...'
- 前根遍历
# pre-order
def PreorderTraversalBinaryTree(root):
if root:
print '%d | ' % root.data,
PreorderTraversalBinaryTree(root.leftChild)
PreorderTraversalBinaryTree(root.rightChild)
- 中根遍历
# in-order
def InorderTraversalBinaryTree(root):
if root:
InorderTraversalBinaryTree(root.leftChild)
print '%d | ' % root.data,
InorderTraversalBinaryTree(root.rightChild)
- 后根遍历
# post-order
def PostorderTraversalBinaryTree(root):
if root:
PostorderTraversalBinaryTree(root.leftChild)
PostorderTraversalBinaryTree(root.rightChild)
print '%d | ' % root.data,
- 按层遍历
# layer-order
def TraversalByLayer(root, length):
stack = []
stack.append(root)
for x in xrange(length):
node = stack[x]
print '%d | ' % node.data,
if node.leftChild:
stack.append(node.leftChild)
if node.rightChild:
stack.append(node.rightChild)
---------------------------------------------------二叉树树的思想重在“递归”, 并不是非要用递归处理,而是去理解二叉树递归的思想------------------------------------------------------------
- 完整代码段
# -*- coding:utf-8 -*- #################
### implement Binary Tree using python
### Hongwing
### 2016-9-4
################# import math class BTNode(object):
"""docstring for BTNode"""
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None # insert element
def InsertElementBinaryTree(root, node):
if root:
if node.data < root.data:
if root.leftChild:
InsertElementBinaryTree(root.leftChild, node)
else:
root.leftChild = node
else:
if root.rightChild:
InsertElementBinaryTree(root.rightChild, node)
else:
root.rightChild = node
else:
return 0 # init a tree
def InitBinaryTree(dataSource, length):
root = BTNode(dataSource[0]) for x in xrange(1,length):
node = BTNode(dataSource[x])
InsertElementBinaryTree(root, node)
return root
print 'Done...' # pre-order
def PreorderTraversalBinaryTree(root):
if root:
print '%d | ' % root.data,
PreorderTraversalBinaryTree(root.leftChild)
PreorderTraversalBinaryTree(root.rightChild) # in-order
def InorderTraversalBinaryTree(root):
if root:
InorderTraversalBinaryTree(root.leftChild)
print '%d | ' % root.data,
InorderTraversalBinaryTree(root.rightChild) # post-order
def PostorderTraversalBinaryTree(root):
if root:
PostorderTraversalBinaryTree(root.leftChild)
PostorderTraversalBinaryTree(root.rightChild)
print '%d | ' % root.data, # layer-order
def TraversalByLayer(root, length):
stack = []
stack.append(root)
for x in xrange(length):
node = stack[x]
print '%d | ' % node.data,
if node.leftChild:
stack.append(node.leftChild)
if node.rightChild:
stack.append(node.rightChild) if __name__ == '__main__':
dataSource = [3, 4, 2, 6, 7, 1, 8, 5]
length = len(dataSource)
BTree = InitBinaryTree(dataSource, length)
print '****NLR:'
PreorderTraversalBinaryTree(BTree)
print '\n****LNR'
InorderTraversalBinaryTree(BTree)
print '\n****LRN'
PostorderTraversalBinaryTree(BTree)
print '\n****LayerTraversal'
TraversalByLayer(BTree, length) --------------------------------------------------------------------------------------------------------------------------------------------------------
简单实现二叉树2(详细代码:https://github.com/201315060025/test/tree/master/data_structure_example)
#二叉树的节点
class Node(object):
def __init__(self,data=None,l_child=None, r_child=None):
self.data = data
self.l_child = l_child
self.r_child = r_child class B_Tree(object):
def __init__(self, node=None):
self.root = node def add(self, item=None):
node = Node(item)
#如果是空树,则直接添到根
if not self.root:
self.root = node
else:
#不为空,则按照 左右顺序 添加节点,这样构建出来的是一棵有序二叉树,且是完全二叉树
my_queue = []
my_queue.append(self.root)
while True:
cur_node = my_queue.pop(0)
if not cur_node.l_child:
cur_node.l_child = node
return
elif not cur_node.r_child:
cur_node.r_child = node
return
else:
my_queue.append(cur_node.l_child)
my_queue.append(cur_node.r_child)
if __name__ == __main__:
data_list = [2,1,3,5,4.6]
tree = B_Tree()
for dt in data_list:
tree.add(dt)
Python实现二叉树及其4种遍历的更多相关文章
- Python实现二叉树的四种遍历
对于一个没学过数据结构这门课程的编程菜鸟来说,自己能理解数据结构中的相关概念,但是自己动手通过Python,C++来实现它们却总感觉有些吃力.递归,指针,类这些知识点感觉自己应用的不够灵活,这是自己以 ...
- PTA 二叉树的三种遍历(先序、中序和后序)
6-5 二叉树的三种遍历(先序.中序和后序) (6 分) 本题要求实现给定的二叉树的三种遍历. 函数接口定义: void Preorder(BiTree T); void Inorder(BiTr ...
- Python 列表(List) 的三种遍历(序号和值)方法
三种遍历列表里面序号和值的方法: 最近学习python这门语言,感觉到其对自己的工作效率有很大的提升,特在情人节这一天写下了这篇博客,下面废话不多说,直接贴代码 #!/usr/bin/env pyth ...
- 基于Java的二叉树的三种遍历方式的递归与非递归实现
二叉树的遍历方式包括前序遍历.中序遍历和后序遍历,其实现方式包括递归实现和非递归实现. 前序遍历:根节点 | 左子树 | 右子树 中序遍历:左子树 | 根节点 | 右子树 后序遍历:左子树 | 右子树 ...
- 二叉树及其三种遍历方式的实现(基于Java)
二叉树概念: 二叉树是每个节点的度均不超过2的有序树,因此二叉树中每个节点的孩子只能是0,1或者2个,并且每个孩子都有左右之分. 位于左边的孩子称为左孩子,位于右边的孩子成为右孩子:以左孩子为根节点的 ...
- C++编程练习(8)----“二叉树的建立以及二叉树的三种遍历方式“(前序遍历、中序遍历、后续遍历)
树 利用顺序存储和链式存储的特点,可以实现树的存储结构的表示,具体表示法有很多种. 1)双亲表示法:在每个结点中,附设一个指示器指示其双亲结点在数组中的位置. 2)孩子表示法:把每个结点的孩子排列起来 ...
- 非递归实现二叉树的三种遍历操作,C++描述
body, table{font-family: 微软雅黑; font-size: 13.5pt} table{border-collapse: collapse; border: solid gra ...
- python 实现二叉树的深度 & 广度优先遍历
什么是树 在计算器科学中,树(英语:tree)是一种抽象数据类型(ADT)或是实现这种抽象数据类型的数据结构,用来模拟具有树状结构性质的数据集合.它是由n(n>0)个有限节点组成一个具有层次关系 ...
- python中的字典两种遍历方式
dic = {"k1":"v1", "k2":"v2"} for k in dic: print(dic[K]) for ...
随机推荐
- Linux/shell命令的实际应用——查看Port占用 netstat
启动1024端口一下,是需要root权限的 该Linux/shell命令主要用于解决: 1.查看某端口是否被占用: 2.查看某端口被哪个进程占用: 3.查看某个进程占用了哪些端口: 比如我tomcat ...
- 创建简单的Telnet实例
step1.先加入库SuperSocket.Common.dll, SuperSocket.SocketBase.dll, SuperSocket.SocketEngine.dll,log4net.d ...
- VMware Player 12.5.0 中文免费版
VMWare Player优点:– 免费的 VMWare Player 体积仅90多MB,相比7百多MB且还要付费的 VMware Workstation 无疑更适合个人用户使用– 主界面清爽简洁,几 ...
- 不止是动态化:Weex项目和阿里无线技术开源方向
这是开发者正在书写的峥嵘岁月.受益开源,回馈社区.阿里巴巴集团已经开源115个项目,并正式加入FSF基金会,Apache基金会,linux 基金会和Xen的顾问团队,并在云栖大会北京峰会宣布AliSQ ...
- 解决sitemesh3装饰页面不能使用freemarker标签问题
如题,这个问题其实在sitemesh2中已经很好的解决了,不过在sitemesh3中可能没有解决,所以要自己写代码解决了,下面我先讲下sitemesh2是如何解决的: <servlet> ...
- 配置eclipse插件
http://blog.csdn.net/zhangyabinsky/article/details/7043435
- HDUOJ---4503 湫湫系列故事——植树节
湫湫系列故事——植树节 Time Limit: 1000/500 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)Total ...
- HDUOJ-------2844Coins
Coins Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submi ...
- Flyod 算法(两两之间的最短路径)
Flyod 算法(两两之间的最短路径)动态规划方法,通过相邻矩阵, 然后把最后的结果存在这么一个矩阵里面,(i,j), #include <iostream> #include <v ...
- DataSnap使用UniDac处理自增长字段
原来使用ado来访问数据库,用在DataSnap中也很方便.后来便一直使用UniDac,可发现UniDac如果用在DataSnap中要比ado麻烦很多,尤其对自增长字段.缺省值的处理上,感觉对Data ...