Python实现重建二叉树的三种方法详解


Posted in Python onJune 23, 2018

本文实例讲述了Python实现重建二叉树的三种方法。分享给大家供大家参考,具体如下:

学习算法中,探寻重建二叉树的方法:

  • 用input 前序遍历顺序输入字符重建
  • 前序遍历顺序字符串递归解析重建
  • 前序遍历顺序字符串堆栈解析重建

如果懒得去看后面的内容,可以直接点击此处本站下载完整实例代码

思路

学习算法中,python 算法方面的资料相对较少,二叉树解析重建更少,只能摸着石头过河。

通过不同方式遍历二叉树,可以得出不同节点的排序。那么,在已知节点排序的前提下,通过某种遍历方式,可以将排序进行解析,从而构建二叉树。

应用上来将,可以用来解析多项式、可以解析网页、xml等。

本文采用前序遍历方式的排列,对已知字符串进行解析,并生成二叉树。新手,以解题为目的,暂未优化,未能体现 Python 简洁、优美。请大牛不吝指正。

首先采用 input 输入

节点类

class treeNode:
 def __init__(self, rootObj = None, leftChild = None, rightChild = None):
  self.key = rootObj
  self.leftChild = None
  self.rightChild = None

input 方法重建二叉树

def createTreeByInput(self, root):
  tmpKey = raw_input("please input a key, input '#' for Null")
  if tmpKey == '#':
   root = None
  else:
   root = treeNode(rootObj=tmpKey)
   root.leftChild = self.createTreeByInput(root.leftChild)
   root.rightChild = self.createTreeByInput(root.rightChild)
  return root

以下两种方法,使用预先编好的字符串,通过 list 方法转换为 list 传入进行解析

myTree 为实例化一个空树

调用递归方法重建二叉树

treeElementList = '124#8##5##369###7##'
 myTree = myTree.createTreeByListWithRecursion(list(treeElementList))
 printBTree(myTree, 0)

递归方法重建二叉树

def createTreeByListWithRecursion(self, preOrderList):
  """
  根据前序列表重建二叉树
  :param preOrder: 输入前序列表
  :return: 二叉树
  """
  preOrder = preOrderList
  if preOrder is None or len(preOrder) <= 0:
   return None
  currentItem = preOrder.pop(0) # 模拟C语言指针移动
  if currentItem is '#':
   root = None
  else:
   root = treeNode(currentItem)
   root.leftChild = self.createTreeByListWithRecursion(preOrder)
   root.rightChild = self.createTreeByListWithRecursion(preOrder)
  return root

调用堆栈方法重建二叉树

treeElementList = '124#8##5##369###7##'
 myTree = myTree.createTreeByListWithStack(list(treeElementList))
 printBTree(myTree, 0)

使用堆栈重建二叉树

def createTreeByListWithStack(self, preOrderList):
 """
 根据前序列表重建二叉树
 :param preOrder: 输入前序列表
 :return: 二叉树
 """
 preOrder = preOrderList
 pStack = SStack()
 # check
 if preOrder is None or len(preOrder) <= 0 or preOrder[0] is '#':
  return None
 # get the root
 tmpItem = preOrder.pop(0)
 root = treeNode(tmpItem)
 # push root
 pStack.push(root)
 currentRoot = root
 while preOrder:
  # get another item
  tmpItem = preOrder.pop(0)
  # has child
  if tmpItem is not '#':
   # does not has left child, insert one
   if currentRoot.leftChild is None:
    currentRoot = self.insertLeft(currentRoot, tmpItem)
    pStack.push(currentRoot.leftChild)
    currentRoot = currentRoot.leftChild
   # otherwise insert right child
   elif currentRoot.rightChild is None:
    currentRoot = self.insertRight(currentRoot, tmpItem)
    pStack.push(currentRoot.rightChild)
    currentRoot = currentRoot.rightChild
  # one child is null
  else:
   # if has no left child
   if currentRoot.leftChild is None:
    currentRoot.leftChild = None
    # get another item fill right child
    tmpItem = preOrder.pop(0)
    # has right child
    if tmpItem is not '#':
     currentRoot = self.insertRight(currentRoot, tmpItem)
     pStack.push(currentRoot.rightChild)
     currentRoot = currentRoot.rightChild
    # right child is null
    else:
     currentRoot.rightChild = None
     # pop itself
     parent = pStack.pop()
     # pos parent
     if not pStack.is_empty():
      parent = pStack.pop()
     # parent become current root
     currentRoot = parent
     # return from right child, so the parent has right child, go to parent's parent
     if currentRoot.rightChild is not None:
      if not pStack.is_empty():
       parent = pStack.pop()
       currentRoot = parent
   # there is a leftchild ,fill right child with null and return to parent
   else:
    currentRoot.rightChild = None
    # pop itself
    parent = pStack.pop()
    if not pStack.is_empty():
     parent = pStack.pop()
    currentRoot = parent
 return root

显示二叉树

def printBTree(bt, depth):
 '''''
 递归打印这棵二叉树,#号表示该节点为NULL
 '''
 ch = bt.key if bt else '#'
 if depth > 0:
  print '%s%s%s' % ((depth - 1) * ' ', '--', ch)
 else:
  print ch
 if not bt:
  return
 printBTree(bt.leftChild, depth + 1)
 printBTree(bt.rightChild, depth + 1)

打印二叉树的代码,采用某仁兄代码,在此感谢。

input 输入及显示二叉树结果

 Python实现重建二叉树的三种方法详解

解析字符串的结果

 Python实现重建二叉树的三种方法详解

完整代码参见:https://github.com/flyhawksz/study-algorithms/blob/master/Class_BinaryTree2.py

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
python解析xml模块封装代码
Feb 07 Python
PHP网页抓取之抓取百度贴吧邮箱数据代码分享
Apr 13 Python
Python 提取dict转换为xml/json/table并输出的实现代码
Aug 28 Python
Python 稀疏矩阵-sparse 存储和转换
May 27 Python
Python基于scapy实现修改IP发送请求的方法示例
Jul 08 Python
python看某个模块的版本方法
Oct 16 Python
PyTorch 1.0 正式版已经发布了
Dec 13 Python
解决Pycharm后台indexing导致不能run的问题
Jun 27 Python
Python GUI编程学习笔记之tkinter事件绑定操作详解
Mar 30 Python
python实现简单猜单词游戏
Dec 24 Python
python压包的概念及实例详解
Feb 17 Python
理解深度学习之深度学习简介
Apr 14 Python
Python根据已知邻接矩阵绘制无向图操作示例
Jun 23 #Python
Python实现的绘制三维双螺旋线图形功能示例
Jun 23 #Python
python和shell监控linux服务器的详细代码
Jun 22 #Python
python中plot实现即时数据动态显示方法
Jun 22 #Python
Python+selenium 获取一组元素属性值的实例
Jun 22 #Python
python selenium 获取标签的属性值、内容、状态方法
Jun 22 #Python
python+selenium打印当前页面的titl和url方法
Jun 22 #Python
You might like
PHP脚本的10个技巧(2)
2006/10/09 PHP
php模板之Phpbean的目录结构
2008/01/10 PHP
PHP中数组定义的几种方法
2013/09/01 PHP
PHP生成短网址的3种方法代码实例
2014/07/08 PHP
php利用smtp类实现电子邮件发送
2015/10/30 PHP
PHP版本升级到7.x后wordpress的一些修改及wordpress技巧
2015/12/25 PHP
根据key删除数组中指定的元素实现方法
2017/03/02 PHP
PHP实现类似于C语言的文件读取及解析功能
2017/09/01 PHP
PHP levenshtein()函数用法讲解
2019/03/08 PHP
js 面向对象的技术创建高级 Web 应用程序
2010/02/25 Javascript
js插件方式打开pdf文件(浏览器pdf插件分享)
2013/12/20 Javascript
Javascript递归打印Document层次关系实例分析
2015/05/15 Javascript
jQuery处理图片加载失败的常用方法
2015/06/08 Javascript
Angular2内置指令NgFor和NgIf详解
2016/08/03 Javascript
微信小程序实现多个按钮的颜色状态转换
2019/02/15 Javascript
使用vue-router在Vue页面之间传递数据的方法
2019/07/15 Javascript
js中调用微信的扫描二维码功能的实现代码
2020/04/11 Javascript
详解Vue之计算属性
2020/06/20 Javascript
[01:55]《走出家门看比赛》——DOTA2 2015国际邀请赛同城线下观战
2015/07/18 DOTA
[01:06:19]DOTA2-DPC中国联赛定级赛 LBZS vs SAG BO3第二场 1月8日
2021/03/11 DOTA
对于Python的Django框架使用的一些实用建议
2015/04/03 Python
在Linux命令行终端中使用python的简单方法(推荐)
2017/01/23 Python
Python实现删除列表中满足一定条件的元素示例
2017/06/12 Python
Python实现基于多线程、多用户的FTP服务器与客户端功能完整实例
2017/08/18 Python
pandas DataFrame实现几列数据合并成为新的一列方法
2018/06/08 Python
解决python中画图时x,y轴名称出现中文乱码的问题
2019/01/29 Python
Django网络框架之HelloDjango项目创建教程
2019/06/06 Python
python读取目录下所有的jpg文件,并显示第一张图片的示例
2019/06/13 Python
python隐藏终端执行cmd命令的方法
2019/06/24 Python
python实现时间序列自相关图(acf)、偏自相关图(pacf)教程
2020/06/03 Python
DVF官方网站:美国时装界尊尚品牌
2017/08/29 全球购物
意大利值得信赖的在线超级药房:PillolaStore
2020/02/05 全球购物
Fenty Beauty官网:蕾哈娜创立的美妆品牌
2021/01/07 全球购物
十岁生日同学答谢词
2014/01/19 职场文书
医学生自我评价
2014/01/27 职场文书
给老婆道歉的话
2015/01/20 职场文书