Python数据结构——二叉树的实现
1. 二叉树
二叉树(binary tree)中的每个节点都不能有多于两个的儿子。
1.1 二叉树列表实现
如上图的二叉树可用列表表示:
tree=['A', #root
['B', #左子树
['D',[],[]],
['E',[],[]]],
['C', #右子树
['F',[],[]],
[]]
]
实现:
def BinaryTree(item):
return [item,[],[]]
def insertLeft(tree,item):
leftSubtree=tree.pop(1)
if leftSubtree:
tree.insert(1,[item,leftSubtree,[]])
else:
tree.insert(1,[item,[],[]])
return tree
def insertRight(tree,item):
rightSubtree=tree.pop(2)
if rightSubtree:
tree.insert(2,[item,[],rightSubtree])
else:
tree.insert(2,[item,[],[]])
return tree
def getLeftChild(tree):
return tree[1]
def getRightChild(tree):
return tree[2]
要实现下图的树:
tree=BinaryTree('a')
insertLeft(tree,'b')
insertRight(tree,'c')
insertRight((getLeftChild(tree)),'d')
insertLeft((getRightChild(tree)),'e')
insertRight((getRightChild(tree)),'f')
1.2 二叉树的类实现
class BinaryTree(object):
def __init__(self,item):
self.key=item
self.leftChild=None
self.rightChild=None
def insertLeft(self,item):
if self.leftChild==None:
self.leftChild=BinaryTree(item)
else:
t=BinaryTree(item)
t.leftChild=self.leftChild
self.leftChild=t
def insertRight(self,item):
if self.rightChild==None:
self.rightChild=BinaryTree(item)
else:
t=BinaryTree(item)
t.rightChild=self.rightChild
self.rightChild=t
2. 表达式树
表达式树(expression tree)的树叶是操作数,其他节点为操作符。
图 ((7+3)*(5-2))的表达式树表示
2.1 根据中缀表达式构造表达式树:
遍历表达式:
1.建立一个空树
2.遇到'(',为当前的Node添加一个left child,并将left child当做当前Node。
3.遇到数字,赋值给当前的Node,并返回parent作为当前Node。
4.遇到('+-*/'),赋值给当前Node,并添加一个Node作为right child,将right child当做当前的Node。
5.遇到')',返回当前Node的parent。
def buildexpressionTree(exp):
tree=BinaryTree('')
stack=[]
stack.append(tree)
currentTree=tree
for i in exp:
if i=='(':
currentTree.insertLeft('')
stack.append(currentTree)
currentTree=currentTree.leftChild
elif i not in '+-*/()':
currentTree.key=int(i)
parent=stack.pop()
currentTree=parent
elif i in '+-*/':
currentTree.key=i
currentTree.insertRight('')
stack.append(currentTree)
currentTree=currentTree.rightChild
elif i==')':
currentTree=stack.pop()
else:
raise ValueError
return tree
上述算法对中缀表达式的写法要求比较繁琐,小括号应用太多,例如要写成(a+(b*c))的形式。
用后缀表达式构建表达式树会方便一点:如果符号是操作数,建立一个单节点并将一个指向它的指针推入栈中。如果符号是一个操作符,从栈中弹出指向两棵树T1和T2的指针并形成一棵新的树,树的根为此操作符,左右儿子分别指向T2和T1.
def build_tree_with_post(exp):
stack=[]
oper='+-*/'
for i in exp:
if i not in oper:
tree=BinaryTree(int(i))
stack.append(tree)
else:
righttree=stack.pop()
lefttree=stack.pop()
tree=BinaryTree(i)
tree.leftChild=lefttree
tree.rightChild=righttree
stack.append(tree)
return stack.pop()
3.树的遍历
3.1 先序遍历(preorder travelsal)
先打印出根,然后递归的打印出左子树、右子树,对应先缀表达式
def preorder(tree,nodelist=None):
if nodelist is None:
nodelist=[]
if tree:
nodelist.append(tree.key)
preorder(tree.leftChild,nodelist)
preorder(tree.rightChild,nodelist)
return nodelist
3.2 中序遍历(inorder travelsal)
先递归的打印左子树,然后打印根,最后递归的打印右子树,对应中缀表达式
def inorder(tree):
if tree:
inorder(tree.leftChild)
print tree.key
inorder(tree.rightChild)
3.3 后序遍历(postorder travelsal)
递归的打印出左子树、右子树,然后打印根,对应后缀表达式
def postorder(tree):
if tree:
for key in postorder(tree.leftChild):
yield key
for key in postorder(tree.rightChild):
yield key
yield tree.key
3.4 表达式树的求值
def postordereval(tree):
operators={'+':operator.add,'-':operator.sub,'*':operator.mul,'/':operator.truediv}
leftvalue=None
rightvalue=None
if tree:
leftvalue=postordereval(tree.leftChild)
rightvalue=postordereval(tree.rightChild)
if leftvalue and rightvalue:
return operators[tree.key](leftvalue,rightvalue)
else:
return tree.key
Python数据结构——二叉树的实现的更多相关文章
- Python数据结构——二叉树
数的特征和定义: 树是一种重要的非线性数据结构,直观地看,它是数据元素(在树中称为结点)按分支关系组织起来的结构,很象自然界中的树那样.树结构在客观世界中广泛存在,如人类社会的族谱和各种社会组织机构都 ...
- python数据结构之树和二叉树(先序遍历、中序遍历和后序遍历)
python数据结构之树和二叉树(先序遍历.中序遍历和后序遍历) 树 树是\(n\)(\(n\ge 0\))个结点的有限集.在任意一棵非空树中,有且只有一个根结点. 二叉树是有限个元素的集合,该集合或 ...
- python数据结构之二叉树的统计与转换实例
python数据结构之二叉树的统计与转换实例 这篇文章主要介绍了python数据结构之二叉树的统计与转换实例,例如统计二叉树的叶子.分支节点,以及二叉树的左右两树互换等,需要的朋友可以参考下 一.获取 ...
- python数据结构树和二叉树简介
一.树的定义 树形结构是一类重要的非线性结构.树形结构是结点之间有分支,并具有层次关系的结构.它非常类似于自然界中的树.树的递归定义:树(Tree)是n(n≥0)个结点的有限集T,T为空时称为空树,否 ...
- python数据结构与算法
最近忙着准备各种笔试的东西,主要看什么数据结构啊,算法啦,balahbalah啊,以前一直就没看过这些,就挑了本简单的<啊哈算法>入门,不过里面的数据结构和算法都是用C语言写的,而自己对p ...
- Python实现二叉树的四种遍历
对于一个没学过数据结构这门课程的编程菜鸟来说,自己能理解数据结构中的相关概念,但是自己动手通过Python,C++来实现它们却总感觉有些吃力.递归,指针,类这些知识点感觉自己应用的不够灵活,这是自己以 ...
- python数据结构与算法——链表
具体的数据结构可以参考下面的这两篇博客: python 数据结构之单链表的实现: http://www.cnblogs.com/yupeng/p/3413763.html python 数据结构之双向 ...
- python数据结构之图的实现
python数据结构之图的实现,官方有一篇文章介绍,http://www.python.org/doc/essays/graphs.html 下面简要的介绍下: 比如有这么一张图: A -> B ...
- Python数据结构与算法--List和Dictionaries
Lists 当实现 list 的数据结构的时候Python 的设计者有很多的选择. 每一个选择都有可能影响着 list 操作执行的快慢. 当然他们也试图优化一些不常见的操作. 但是当权衡的时候,它们还 ...
随机推荐
- B. Fox And Two Dots
B. Fox And Two Dots time limit per test 2 seconds memory limit per test 256 megabytes input standard ...
- cocos2d-x使用ant打包
1. 下载apache-ant-1.9.3,然后添加环境变量ANT_HOME = D:\dev_envir\apache-ant-1.9.3(你自己的ant根目录),再在path中添加路径:%ANT_ ...
- 高效Count
SQL Server快速查询某张表的当前行数 传统做法可能是select count(1) 但是往往会比较慢.推荐如下做法: SELECT ISNULL(MAX(rowcnt), 0) Curre ...
- linux nginx启动 重启 关闭命令
启动操作 nginx -c /usr/local/nginx/conf/nginx.conf -c参数指定了要加载的nginx配置文件路径 停止操作停止操作是通过向nginx进程发送信号来进行的 步骤 ...
- CSS实现标题超出宽度省略号来表示
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...
- No Dialect mapping for JDBC type: -1
MySQL数据库中有张表的字段是text,查询出来后对应的java类型是String,Dialect设置为org.hibernate.dialect.MySQLDialect 运行的时候报错:No D ...
- Redis 命令 - Transactions
DISCARD Discard all commands issued after MULTI 127.0.0.1:6379> MGET bank:A:account bank:B:accoun ...
- CSS之照片翻转
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="C ...
- CF下Split的使用
在Compact Framework 下 String的Split不能正确的处理 字符串 分割字符串 如对字符串 "abcfdef12abcedef23" 以"ef&qu ...
- centos6.5下磁盘分区及挂载
1..查看磁盘空间 2.磁盘分区 3.格式化分区 4.挂载/卸载