二叉树

简介:

  二叉树是每个结点最多有两个子树的树结构。通常子树被称作“左子树”(left subtree)和“右子树”(right subtree)。

二叉树二叉树的链式存储:

  将二叉树的节点定义为一个对象,节点之间通过类似链表的链接方式来连接。

节点定义:

      

二叉树的遍历:

  二叉树的遍历方式:

  前序遍历:EACBDGF

  中序遍历:ABCDEGF

  后序遍历:BDCAFGE

  层次遍历:EAGCFBD

代码实现:

# _*_ coding=utf-8 _*_

"""
实现一个二叉树结果,并进行遍历
E
/ \
A G
\ \
C F
/ \
B D
"""
from collections import deque class BinaryTree(object):
def __init__(self, data):
self.data = data
self.child_l = None
self.child_r = None # 创建
a = BinaryTree("A")
b = BinaryTree("B")
c = BinaryTree("C")
d = BinaryTree("D")
e = BinaryTree("E")
f = BinaryTree("F")
g = BinaryTree("G") # 构造节点关系
e.child_l = a
e.child_r = g
a.child_r = c
c.child_l = b
c.child_r = d
g.child_r = f # 设置根
root = e def pre_order(tree):
"""
前序遍历:root -> child_l -> child_r
:param tree: the root of tree
:return:
"""
if tree:
print(tree.data, end=',')
# print("")
pre_order(tree.child_l)
pre_order(tree.child_r) def in_order(tree):
"""
中序遍历:child_l -> root -> child_r
:param tree:
:return:
"""
if tree:
in_order(tree.child_l)
print(tree.data, end=',')
in_order(tree.child_r) def post_order(tree):
"""
后序遍历:child_l -> child_r -> root
:param tree:
:return:
"""
if tree:
post_order(tree.child_l)
post_order(tree.child_r)
print(tree.data, end=',') def level_order(tree):
"""
层次遍历:E -> AG -> CF -> BD
使用队列实现
:param tree:
:return:
"""
queue = deque()
queue.append(tree) # 先把根添加到队列
while len(queue): # 队列不为空
node = queue.popleft()
print(node.data, end=',')
if node.child_l:
queue.append(node.child_l)
if node.child_r:
queue.append(node.child_r) pre_order(root)
print('')
in_order(root)
print('')
post_order(root)
print('')
level_order(root)

  

最新文章

  1. shell脚本变量
  2. Scalding初探之三:Hadoop实战
  3. 关于Java的数据结构HashMap,ArrayList的使用总结及使用场景和原理分析
  4. SparkSQL使用之Thrift JDBC server
  5. 学习CentOS7笔记(一)
  6. Mac下安装HBase及详解
  7. 初次接触pyqt
  8. Objective-C 学习笔记(Day 2)
  9. CH Round #53 -【Nescafé 32】杯NOIP模拟赛
  10. matlab画甘特图
  11. jstree使用小结(三)
  12. linux系统下phpstudy里的mysql使用方法
  13. SmartSql Config配置
  14. 2018-2019 20165221 网络对抗 Exp5 MSF基础
  15. 解决win系统无法安装.NET Framework 4.0 4.6 原因是HRESULT0xc8000222
  16. java中的缓冲流!
  17. 多项式乘法(FFT)学习笔记
  18. 【SVN】CentOS7.0下搭建SVN服务器
  19. GitHub linux 提交文件及403错误处理
  20. jvm虚拟机--垃圾回收子系统

热门文章

  1. python基础数据类型--元组(tuple)
  2. ubuntu 中加速pip指令下载插件的速度
  3. laravel.01.一些细节
  4. PostAsync与GetAsync
  5. Tunning spark
  6. APIO 2010 特别行动队 斜率优化DP
  7. 干货分享|Critique Essay写作解析
  8. CF1141D Colored Boots
  9. 【转载】WebDriver拾级而上·之零 WebDriver理论
  10. IT日常技能:VMware网络配置