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 ValueError: invalid literal for int() with base 10 实用解决方法
Jun 21 Python
python实现单线程多任务非阻塞TCP服务端
Jun 13 Python
python自动化报告的输出用例详解
May 30 Python
解决DataFrame排序sort的问题
Jun 07 Python
python super的使用方法及实例详解
Sep 25 Python
python内打印变量之%和f的实例
Feb 19 Python
Django REST framwork的权限验证实例
Apr 02 Python
Python3中小括号()、中括号[]、花括号{}的区别详解
Nov 15 Python
Python3+PyCharm+Django+Django REST framework配置与简单开发教程
Feb 16 Python
Pyside2中嵌入Matplotlib的绘图的实现
Feb 22 Python
python基于机器学习预测股票交易信号
May 25 Python
Python 的演示平台支持 WSGI 接口的应用
Apr 20 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和MySQL保存和输出图片
2006/10/09 PHP
php 启动报错如何解决
2014/01/17 PHP
[原创]php简单隔行变色功能实现代码
2016/07/09 PHP
php简单压缩css样式示例
2016/09/22 PHP
JavaScript子窗口ModalDialog中操作父窗口对像
2012/12/11 Javascript
Jquery通过Ajax访问XML数据的小例子
2013/11/18 Javascript
使用phantomjs进行网页抓取的实现代码
2014/09/29 Javascript
解决ueditor jquery javascript 取值问题
2014/12/30 Javascript
javascript中var的重要性分析
2015/02/11 Javascript
JavaScript中var关键字的使用详解
2015/08/14 Javascript
AngularJS入门教程之REST和定制服务详解
2016/08/19 Javascript
jquery心形点赞关注效果的简单实现
2016/11/14 Javascript
angularJS 发起$http.post和$http.get请求的实现方法
2017/05/18 Javascript
利用node实现一个批量重命名文件的函数
2017/12/21 Javascript
基于vue.js无缝滚动效果
2018/01/25 Javascript
基于node+vue实现简单的WebSocket聊天功能
2020/02/01 Javascript
javascript+css实现进度条效果
2020/03/25 Javascript
vue+element_ui上传文件,并传递额外参数操作
2020/12/05 Vue.js
[04:09]2014DOTA2国际邀请赛Ti西雅图 历届冠军相继出局 BBC综述今日比赛
2014/07/20 DOTA
Windows下Python的Django框架环境部署及应用编写入门
2016/03/10 Python
Python多进程并发与多线程并发编程实例总结
2018/02/08 Python
python中找出numpy array数组的最值及其索引方法
2018/04/17 Python
python实现名片管理系统
2018/11/29 Python
python3+django2开发一个简单的人员管理系统过程详解
2019/07/23 Python
python2使用bs4爬取腾讯社招过程解析
2019/08/14 Python
matlab中二维插值函数interp2的使用详解
2020/04/22 Python
Python爬取网页信息的示例
2020/09/24 Python
PyQT5速成教程之Qt Designer介绍与入门
2020/11/02 Python
Django配置跨域并开发测试接口
2020/11/04 Python
css3 旋转按钮 使用CSS3创建一个旋转可变色按钮
2012/12/31 HTML / CSS
css3 伪元素和伪类选择器详解
2014/09/04 HTML / CSS
以工厂直接定价的传奇性能:Ben Hogan Golf
2019/01/04 全球购物
党员志愿者活动方案
2014/08/28 职场文书
三问三解心得体会
2014/09/05 职场文书
幼儿园教师教学反思
2016/03/02 职场文书
Python如何解决secure_filename对中文不支持问题
2021/07/16 Python