树是数据结构中常用到的一种结构,其实现较栈和队稍为复杂一些。若树中的所有节点的孩子节点数量不超过2个,则该为一个二叉树。二叉树可用于查找和排序等。二叉树的主要操作有:建树,遍历等。遍历是树中的一个最为重要的操作,可分为深度优先遍历和广度优先遍历。其中,尝试优先遍历又可分为先序遍历,中序遍历和后序遍历。深度优先遍历可使用递规来实现,也可以用栈和队通过循环实现。后序的非递规遍历,比其他两种遍历稍为复杂些。

下面给出一个python实现二叉树的例子:

class Node(object):
def __init__(self, data = -1, lchild = None, rchild = None):
self.data = data
self.lchild = lchild
self.rchild = rchild class BinaryTree(object):
def __init__(self):
self.root = Node() def add(self, data):
node = Node(data)
if self.isEmpty():
self.root = node
else:
tree_node = self.root
queue = []
queue.append(self.root) while queue:
tree_node = queue.pop(0)
if tree_node.lchild == None:
tree_node.lchild = node
return
elif tree_node.rchild == None:
tree_node.rchild = node
return
else:
queue.append(tree_node.lchild)
queue.append(tree_node.rchild) def pre_order(self, start):
node = start
if node == None:
return print node.data,
if node.lchild == None and node.rchild == None:
return
self.pre_order(node.lchild)
self.pre_order(node.rchild) def pre_order_loop(self):
if self.isEmpty():
return stack = []
node = self.root
while node or stack:
while node:
print node.data,
stack.append(node)
node = node.lchild
if stack:
node = stack.pop()
node = node.rchild def in_order(self, start):
node = start
if node == None:
return
self.in_order(node.lchild)
print node.data,
self.in_order(node.rchild) def in_order_loop(self):
if self.isEmpty():
returen stack = []
node = self.root
while node or stack:
while node:
stack.append(node)
node = node.lchild if stack:
node = stack.pop()
print node.data,
node = node.rchild def post_order(self, start):
node = start
if node == None:
return
self.post_order(node.lchild)
self.post_order(node.rchild)
print node.data, def post_order_loop(self):
if self.isEmpty():
return node = self.root
stack = []
queue = []
queue.append(node)
while queue:
node = queue.pop()
if node.lchild:
queue.append(node.lchild)
if node.rchild:
queue.append(node.rchild)
stack.append(node)
while stack:
print stack.pop().data, #if lchild and rchild are None or lchild and rchild are printed, print the parent node node and pop out of the stack
#else lchild and rchild push into the stack
def post_order_loop1(self):
if self.isEmpty():
return stack = []
top = -1
node = self.root
stack.append(node)
#we need to recognize the last printed node
top += 1
pre = None
while stack:
node = stack[-1]
if node.lchild is None and node.rchild is None:
print node.data,
pre = node
top -= 1
elif not pre and (node.lchild == pre or node.rchild == pre):
print node.data,
pre = node
top -= 1
else:
if node.rchild:
if top < len(stack)-1:
stack[top] = node.rchild
else:
stack.append(node.rchild)
if node.lchild:
if top < len(stack)-1:
stack[top] = node.lchild
else:
stack.append(node.lchild) def level_order(self):
node = self.root
if node == None:
return queue = []
queue.append(node) while queue:
node = queue.pop(0)
print node.data,
if node.rchild:
queue.append(node.rchild)
if node.lchild:
queue.append(node.lchild)
print def isEmpty(self):
return True if self.root.data == -1 else False if __name__ == '__main__':
arr = []
for i in range(10):
arr.append(i)
print arr tree = BinaryTree()
for i in arr:
tree.add(i)
print 'level_order:'
tree.level_order()
print 'pre order:'
tree.pre_order(tree.root)
print '\npre order loop:'
tree.pre_order_loop()
print '\nin_order:'
tree.in_order(tree.root)
print '\nin_order loop:'
tree.in_order_loop()
print '\npost_order:'
tree.post_order(tree.root)
print '\npost_order_loop:'
tree.post_order_loop()
print '\npost_order_loop1:'
tree.post_order_loop1()

基础数据结构 之 树(python实现)的更多相关文章

  1. python数据结构之树和二叉树(先序遍历、中序遍历和后序遍历)

    python数据结构之树和二叉树(先序遍历.中序遍历和后序遍历) 树 树是\(n\)(\(n\ge 0\))个结点的有限集.在任意一棵非空树中,有且只有一个根结点. 二叉树是有限个元素的集合,该集合或 ...

  2. 用Python实现数据结构之树

    树 树是由根结点和若干颗子树构成的.树是由一个集合以及在该集合上定义的一种关系构成的.集合中的元素称为树的结点,所定义的关系称为父子关系.父子关系在树的结点之间建立了一个层次结构.在这种层次结构中有一 ...

  3. 【UOJ228】基础数据结构练习题(线段树)

    [UOJ228]基础数据结构练习题(线段树) 题面 UOJ 题解 我们来看看怎么开根? 如果区间所有值都相等怎么办? 显然可以直接开根 如果\(max-sqrt(max)=min-sqrt(min)\ ...

  4. 小白学 Python(9):基础数据结构(列表)(上)

    人生苦短,我选Python 前文传送门 小白学 Python(1):开篇 小白学 Python(2):基础数据类型(上) 小白学 Python(3):基础数据类型(下) 小白学 Python(4):变 ...

  5. 小白学 Python(10):基础数据结构(列表)(下)

    人生苦短,我选Python 前文传送门 小白学 Python(1):开篇 小白学 Python(2):基础数据类型(上) 小白学 Python(3):基础数据类型(下) 小白学 Python(4):变 ...

  6. 小白学 Python(11):基础数据结构(元组)

    人生苦短,我选Python 前文传送门 小白学 Python(1):开篇 小白学 Python(2):基础数据类型(上) 小白学 Python(3):基础数据类型(下) 小白学 Python(4):变 ...

  7. 小白学 Python(13):基础数据结构(字典)(下)

    人生苦短,我选Python 前文传送门 小白学 Python(1):开篇 小白学 Python(2):基础数据类型(上) 小白学 Python(3):基础数据类型(下) 小白学 Python(4):变 ...

  8. 小白学 Python(12):基础数据结构(字典)(上)

    人生苦短,我选Python 前文传送门 小白学 Python(1):开篇 小白学 Python(2):基础数据类型(上) 小白学 Python(3):基础数据类型(下) 小白学 Python(4):变 ...

  9. 小白学 Python(14):基础数据结构(集合)(上)

    人生苦短,我选Python 前文传送门 小白学 Python(1):开篇 小白学 Python(2):基础数据类型(上) 小白学 Python(3):基础数据类型(下) 小白学 Python(4):变 ...

随机推荐

  1. Eclipse修改编码后乱码解决

    Eclipse用了一段时间,都是用的gbk编码的,突然想要规范下,强迫症犯了,于是将在Window->Preference->Appearances->Workspace修改Text ...

  2. 史上最全面的FRM与CFA的区别对比分析,适合新人看

    简单地自我介绍:本人于纽约完成了研究生阶段的学习后,在华尔街混迹了几年的时间,已获取FRM证书,正在积极准备CFA. 上海财经大学FRM培训中心前言导读 经常看到CFA持证人平均年收入为$XXX之类的 ...

  3. 2013 ACM/ICPC Asia Regional Changsha Online - E

    第一个被板刷的题 取余 依次算在周几 #include <iostream> #include<cstdio> #include<cstring> #include ...

  4. [swustoj 679] Secret Code

    Secret Code 问题描述 The Sarcophagus itself is locked by a secret numerical code. When somebody wants to ...

  5. HDU 1503 Advanced Fruits (LCS,变形)

    题意: 给两个水果名,要求他们的LCS部分只输出1次,其他照常输出,但是必须保持原来的顺序! 思路: 求LCS是常规的,但是输出麻烦了,要先求LCS,再标记两串中的所有LCS字符,在遇到LCS字符时, ...

  6. [Bhatia.Matrix Analysis.Solutions to Exercises and Problems]ExI.2.7

    The set of all invertible matrices is a dense open subset of the set of all $n\times n$ matrices. Th ...

  7. Memcache缓存与Mongodb数据库的优势和应用

    先说说自己对 Memcache和Mongodb的一些看法,主要是抛砖引玉了,希望看到大家的意见和补充. Memcache Memcache的优势我觉得总结下来主要体现在: 1) 分布式.可以由10台拥 ...

  8. SQL Server 外键约束的例子

    外键约束的测试表与测试数据 -- 创建测试主表. ID 是主键. CREATE TABLE test_main ( id INT, value ), PRIMARY KEY(id) ); -- 创建测 ...

  9. 【转】Linux(Ubuntu)下面SecureCRT 完全破解

    仅供测试, 勿用作商业用途.首先要到vandyke网站下载一个securecrt, 需要注册.http://www.vandyke.com/download/securecrt/download.ht ...

  10. tpl + ccr

    不是非此即彼的场景.如下混合使用CCR+TPL的代码说明问题:It's not an either/or scenario.You can intermix CCR and TPL code like ...