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种遍历的更多相关文章

  1. Python实现二叉树的四种遍历

    对于一个没学过数据结构这门课程的编程菜鸟来说,自己能理解数据结构中的相关概念,但是自己动手通过Python,C++来实现它们却总感觉有些吃力.递归,指针,类这些知识点感觉自己应用的不够灵活,这是自己以 ...

  2. PTA 二叉树的三种遍历(先序、中序和后序)

    6-5 二叉树的三种遍历(先序.中序和后序) (6 分)   本题要求实现给定的二叉树的三种遍历. 函数接口定义: void Preorder(BiTree T); void Inorder(BiTr ...

  3. Python 列表(List) 的三种遍历(序号和值)方法

    三种遍历列表里面序号和值的方法: 最近学习python这门语言,感觉到其对自己的工作效率有很大的提升,特在情人节这一天写下了这篇博客,下面废话不多说,直接贴代码 #!/usr/bin/env pyth ...

  4. 基于Java的二叉树的三种遍历方式的递归与非递归实现

    二叉树的遍历方式包括前序遍历.中序遍历和后序遍历,其实现方式包括递归实现和非递归实现. 前序遍历:根节点 | 左子树 | 右子树 中序遍历:左子树 | 根节点 | 右子树 后序遍历:左子树 | 右子树 ...

  5. 二叉树及其三种遍历方式的实现(基于Java)

    二叉树概念: 二叉树是每个节点的度均不超过2的有序树,因此二叉树中每个节点的孩子只能是0,1或者2个,并且每个孩子都有左右之分. 位于左边的孩子称为左孩子,位于右边的孩子成为右孩子:以左孩子为根节点的 ...

  6. C++编程练习(8)----“二叉树的建立以及二叉树的三种遍历方式“(前序遍历、中序遍历、后续遍历)

    树 利用顺序存储和链式存储的特点,可以实现树的存储结构的表示,具体表示法有很多种. 1)双亲表示法:在每个结点中,附设一个指示器指示其双亲结点在数组中的位置. 2)孩子表示法:把每个结点的孩子排列起来 ...

  7. 非递归实现二叉树的三种遍历操作,C++描述

    body, table{font-family: 微软雅黑; font-size: 13.5pt} table{border-collapse: collapse; border: solid gra ...

  8. python 实现二叉树的深度 & 广度优先遍历

    什么是树 在计算器科学中,树(英语:tree)是一种抽象数据类型(ADT)或是实现这种抽象数据类型的数据结构,用来模拟具有树状结构性质的数据集合.它是由n(n>0)个有限节点组成一个具有层次关系 ...

  9. python中的字典两种遍历方式

    dic = {"k1":"v1", "k2":"v2"} for k in dic: print(dic[K]) for ...

随机推荐

  1. exception PLS-00403: expression 'V_END' cannot be used as an INTO-target of a SELECT/FETCH statement

      exception PLS-00403: expression 'V_END' cannot be used as an INTO-target of a SELECT/FETCH stateme ...

  2. js时间转换,能够把时间转换成yyyymmdd格式或yyyymm格式

    //type为1则转换成yyyymmdd格式,type为2则转换成yyyymm格式 function formatTime(time,type){ var temp_time=new Number(t ...

  3. 各种HTTPS站点的SSL证书 ,扩展SSL证书,密钥交换和身份验证机制汇总

    各种HTTPS站点的SSL证书 ,扩展SSL证书,密钥交换和身份验证机制汇总 一份常见的 HTTPS 站点使用的证书和数据加密技术列表,便于需要时比较参考,将持续加入新的 HTTP 站点,这里给出的信 ...

  4. 转载:substr() mb_substr() mb_subcut区别与联系

    substr() $rest = substr("abcdef", 1); //bcdef $rest = substr("abcdef", 1,5); //b ...

  5. Tomcat路径下目录的介绍

           本文转自:http://blog.csdn.net/u013132035/article/details/54949593 下图是TOMCAT的路径下目录的截图. 目录有:backup. ...

  6. SpringBoot使用拦截器

    SpringBoot的拦截器只能拦截流经DispatcherServlet的请求,对于自定义的Servlet无法进行拦截. SpringMVC中的拦截器有两种:HandlerInterceptor和W ...

  7. python标准库介绍——27 random 模块详解

    ==random 模块== "Anyone who considers arithmetical methods of producing random digits is, of cour ...

  8. java基础常见问题和eclipse常用快捷键

    一.java常用库 java.lang中 StringBuffer,StringBuilder,System,Runtime,Math java.util Date,Calendar,Random j ...

  9. ActiveMQ + NodeJS + Stomp 入门

    NodeJS + stomp-client 入门 准备 下载ActiveMQ并安装 执行bin\win32\activemq.bat启动MQ服务 打开http://localhost:8161/adm ...

  10. mysql分组取每组前几条记录(排序)

    首先来造一部分数据,表mygoods为商品表,cat_id为分类id,goods_id为商品id,status为商品当前的状态位(1:有效,0:无效). CREATE TABLE `mygoods` ...