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 相关文章推荐
Pyhthon中使用compileall模块编译源文件为pyc文件
Apr 28 Python
python读写二进制文件的方法
May 09 Python
Python中scatter函数参数及用法详解
Nov 08 Python
攻击者是如何将PHP Phar包伪装成图像以绕过文件类型检测的(推荐)
Oct 11 Python
Python tkinter的grid布局及Text动态显示方法
Oct 11 Python
Django的用户模块与权限系统的示例代码
Jul 24 Python
在macOS上搭建python环境的实现方法
Aug 13 Python
详解使用PyInstaller将Pygame库编写的小游戏程序打包为exe文件
Aug 23 Python
在OpenCV里使用特征匹配和单映射变换的代码详解
Oct 23 Python
Python进程池Pool应用实例分析
Nov 27 Python
python中通过pip安装库文件时出现“EnvironmentError: [WinError 5] 拒绝访问”的问题及解决方案
Aug 11 Python
python办公自动化之excel的操作
May 23 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
destoon安全设置中需要设置可写权限的目录及文件
2014/06/21 PHP
PHP采用超长(超大)数字运算防止数字以科学计数法显示的方法
2016/04/01 PHP
PHP图像处理 imagestring添加图片水印与文字水印操作示例
2020/02/06 PHP
js 对联广告、漂浮广告封装类(IE,FF,Opera,Safari,Chrome
2009/11/26 Javascript
JavaScript入门之对象与JSON详解
2011/10/21 Javascript
ASP.NET jQuery 实例1(在TextBox里面创建一个默认提示)
2012/01/13 Javascript
使用闭包对setTimeout进行简单封装避免出错
2013/07/10 Javascript
window.open打开页面居中显示的示例代码
2013/12/27 Javascript
avascript中的自执行匿名函数应用示例
2014/09/15 Javascript
一个JavaScript递归实现反转数组字符串的实例
2014/10/14 Javascript
JS模式之简单的订阅者和发布者模式完整实例
2015/06/30 Javascript
干货分享:让你分分钟学会javascript闭包
2015/12/25 Javascript
JS实现合并json对象的方法
2017/10/10 Javascript
vue单个组件实现无限层级多选菜单功能
2018/04/10 Javascript
微信小程序页面缩放式侧滑效果的实现代码
2018/11/15 Javascript
vue.js的vue-cli脚手架中使用百度地图API的实例
2019/01/21 Javascript
小白教程|一小时上手最流行的前端框架vue(推荐)
2019/04/10 Javascript
Vue源码探究之虚拟节点的实现
2019/04/17 Javascript
angular中的post请求处理示例详解
2020/06/30 Javascript
Vue路由切换页面不更新问题解决方案
2020/07/10 Javascript
JS倒计时两种实现方式代码实例
2020/07/27 Javascript
详解JavaScript中的this指向问题
2021/02/05 Javascript
Python 文件重命名工具代码
2009/07/26 Python
Python 爬虫学习笔记之正则表达式
2016/09/21 Python
python zip,lambda,map函数代码实例
2020/04/04 Python
python实现测试工具(一)——命令行发送get请求
2020/10/19 Python
英国、欧洲和全球租车服务:Avis英国
2016/08/29 全球购物
泰海淘:泰国king Power王权免税集团旗下跨境海淘综合型电商
2020/07/26 全球购物
请解释一下webService? 如何用.net实现webService
2014/06/09 面试题
中医药大学市场营销专业自荐信
2013/09/29 职场文书
团日活动总结书
2014/05/08 职场文书
国贸专业求职信
2014/06/28 职场文书
出售房屋协议书范本
2014/10/06 职场文书
机关干部纪律作风整顿心得体会
2016/01/23 职场文书
详细聊聊关于Mysql联合查询的那些事儿
2021/10/24 MySQL
CSS3实现指纹特效代码
2022/03/17 HTML / CSS