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. java 类名.class、object.getClass()和Class.forName()的区别 精析

        1.介绍 getClass()介绍 java是面向对象语言,即万物皆对象,所有的对象都直接或间接继承自Object类: Object类中有getClass()方法,通过这个方法就可以获得一个实 ...

  2. asp.net MVC在IIS7或7.5上的发布问题

    按照网上的做法,开启了ISAPI和CGI限制C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll 应用程序池也设置好了,可是就是 ...

  3. JQuery 在线参考手册

    官方JQuery API  http://api.jquery.com/ 在线参考手册    http://www.w3school.com.cn/jquery/index.asp 在线参考手册1   ...

  4. Linux下MySQL链接被防火墙阻止

    Linux下安装了MySQL,不能从其它机器访问 帐号已经授权从任意主机进行访问 vi /etc/sysconfig/iptables 在后面添加 -A RH-Firewall-1-INPUT -m ...

  5. iOS-高仿通讯录之商品索引排序搜索

    概述 TableView添加右侧索引, 将数据按照索引分组排序, 并添加搜索功能且在搜索界面复用当前页面. 详细 代码下载:http://www.demodashi.com/demo/10696.ht ...

  6. genymotion安装(unknown generic error)及配置在Android studio环境中

    /*转载请注明出处.本文地址:http://write.blog.csdn.net/postedit/44261371*/ genymotion模拟器的长处我就不阐述了,一个字:快!! .如今来说一下 ...

  7. JavaScript-jQuery报TypeError $(...) is null错误(jQuery失效)解决办法

    出现这种错误一般都是jQuery的$方法被覆盖, 解决办法: 1.把$改为jQuery使用 jQuery.noConflict();//将变量$的控制权让渡给给其他插件或库 jQuery(functi ...

  8. springmvc最优化

    java代码 package com.tgb.web.controller.annotation; import javax.servlet.http.HttpServletRequest; impo ...

  9. 浅析iOS tableview的selectRowAtIndexPath选中无效(默认选中cell无效)

    可能很多人都遇到过这种情况: tableview列表,有时加载完,需要默认选中某一行,给予选中效果:或者需要执行某行的点击事件. 我们举例: 比如我想默认选中第一行 可能我们第一个想法就是这样: [m ...

  10. C#取得页面URL信息

    我們在開發網頁應用程式,時常需要去解析網址(Request.Url)的每個片段,進行一些判斷.例如說 "http://localhost:1897/News/Press/Content.as ...