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两种遍历字典(dict)的方法比较
May 29 Python
Python功能键的读取方法
May 28 Python
使用python 3实现发送邮件功能
Jun 15 Python
python保存文件方法小结
Jul 27 Python
python reverse反转部分数组的实例
Dec 13 Python
详解python3中用HTMLTestRunner.py报ImportError: No module named 'StringIO'如何解决
Aug 27 Python
浅谈python print(xx, flush = True) 全网最清晰的解释
Feb 21 Python
Django实现图片上传功能步骤解析
Apr 22 Python
python 追踪except信息方式
Apr 25 Python
Python加速程序运行的方法
Jul 29 Python
python将下载到本地m3u8视频合成MP4的代码详解
Nov 24 Python
Python正则表达式中flags参数的实例详解
Apr 01 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通过iconv将字符串从GBK转换为UTF8字符集
2011/07/18 PHP
PHP基于cookie与session统计网站访问量并输出显示的方法
2016/01/15 PHP
PHP并发场景的三种解决方案代码实例
2021/02/27 PHP
JScript中的undefined和&quot;undefined&quot;的区别
2007/03/08 Javascript
javascript 避免闭包引发的问题
2009/03/17 Javascript
js 代码集(学习js的朋友可以看下)
2009/07/22 Javascript
jQuery cdn使用介绍
2013/05/08 Javascript
探讨javascript是不是面向对象的语言
2013/11/21 Javascript
jQuery中使用data()方法读取HTML5自定义属性data-*实例
2014/04/11 Javascript
实例详解Nodejs 保存 payload 发送过来的文件
2016/01/14 NodeJs
Node.js实现兼容IE789的文件上传进度条
2016/09/02 Javascript
Express之get,pos请求参数的获取
2017/05/02 Javascript
详解Vue路由钩子及应用场景(小结)
2017/11/07 Javascript
AngularJs 禁止模板缓存的方法
2017/11/28 Javascript
vue实现自定义多选与单选的答题功能
2018/07/05 Javascript
JavaScript实现创建自定义对象的常用方式总结
2018/07/09 Javascript
Node.js搭建WEB服务器的示例代码
2018/08/15 Javascript
vue watch深度监听对象实现数据联动效果
2018/08/16 Javascript
JQuery的加载和选择器用法简单示例
2019/05/13 jQuery
通过实例解析JavaScript常用排序算法
2020/09/02 Javascript
jQuery实现可以扩展的日历
2020/12/01 jQuery
[05:31]DOTA2英雄梦之声_第08期_莉娜
2014/06/23 DOTA
python正则表达式re之compile函数解析
2017/10/25 Python
程序员写Python时的5个坏习惯,你有几条?
2018/11/26 Python
Pandas之DataFrame对象的列和索引之间的转化
2019/06/25 Python
python实现车牌识别的示例代码
2019/08/05 Python
Pytorch保存模型用于测试和用于继续训练的区别详解
2020/01/10 Python
美国最大的电子宠物训练产品制造商:PetSafe
2018/10/12 全球购物
德国帽子专家:Hutshopping
2019/11/03 全球购物
浙江文明网签名寄语
2014/01/18 职场文书
蟋蟀的住宅教学反思
2014/04/26 职场文书
大学生社会实践方案
2014/05/11 职场文书
酒店节能减排方案
2014/05/26 职场文书
工作目标责任书
2014/07/23 职场文书
学风建设演讲稿
2014/09/12 职场文书
vue二维数组循环嵌套方式 循环数组、循环嵌套数组
2022/04/24 Vue.js