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 ...
随机推荐
- 简单的 Helper 封装 -- CookieHelper
using System; using System.Web; namespace ConsoleApplication5 { /// <summary> /// Cookie 助手 // ...
- python之函数用法__setattr__
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法__setattr__ #http://www.cnblogs.com/hongfei ...
- 【laravel5.4】php artisan migrate报错:Specified key was too long; max key length is 767 bytes
1.原因:在进行 迁移文件生成时,程序并未给varchar类型字段设置 合适的长度,导致报错. 2.解决办法:找到database/ 目标迁移文件,修改其中类型为string的字段长度,建议不要超过2 ...
- What is the difference between J2EE and Spring
来自于:https://www.quora.com/What-is-the-difference-between-J2EE-and-Spring Lot of people specially tho ...
- js 动态增加行删除行
<body> <table id="tableID" border="1" align="center" width=&q ...
- Archlive新年第一棒: 基于2.6.37稳定内核的archlive20110107
先上图,再来说明吧... 下载地址: http://u.115.com/file/t2cd0ea120 先上个本机器运行teamviewer的效果图吧... 如假包换的 2.6.37, 担保是目前最 ...
- 【LeetCode】149. Max Points on a Line
Max Points on a Line Given n points on a 2D plane, find the maximum number of points that lie on the ...
- eclipse3.3插件更新攻略
eclipse有种在线(需有网络)安装插件方法,随着eclipse版本的不同,UI会有所改变.这里记录下e3.3的安装方法 1.选择Find and Install(查找并且安装)选项 ...
- RabbitMQ消息队列(一): Detailed Introduction 详细介绍[转]
1. 历史 RabbitMQ是一个由erlang开发的AMQP(Advanced Message Queue )的开源实现.AMQP 的出现其实也是应了广大人民群众的需求,虽然在同步消息通讯的世界里有 ...
- iOS - UIPasteboard
前言 NS_CLASS_AVAILABLE_IOS(3_0) __TVOS_PROHIBITED __WATCHOS_PROHIBITED @interface UIPasteboard : NSOb ...