侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   149

本文实例讲述了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 输入及显示二叉树结果

 

解析字符串的结果

 

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

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

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


  • 上一条:
    Python实现绘制双柱状图并显示数值功能示例
    下一条:
    Python根据已知邻接矩阵绘制无向图操作示例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客