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和set方法的教程
Apr 27 Python
详解在Python程序中自定义异常的方法
Oct 16 Python
Python实现的直接插入排序算法示例
Apr 29 Python
python3 selenium 切换窗口的几种方法小结
May 21 Python
Pycharm 操作Django Model的简单运用方法
May 23 Python
Python二叉树定义与遍历方法实例分析
May 25 Python
python控制windows剪贴板,向剪贴板中写入图片的实例
May 31 Python
使用Python操作ArangoDB的方法步骤
Feb 02 Python
python使用梯度下降算法实现一个多线性回归
Mar 24 Python
python 双循环遍历list 变量判断代码
May 04 Python
Python Pandas 对列/行进行选择,增加,删除操作
May 17 Python
Python中递归以及递归遍历目录详解
Oct 24 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的call_user_func传reference引发的思考
2010/07/23 PHP
PHP修改session_id示例代码
2014/01/08 PHP
php中的动态调用实例分析
2015/01/07 PHP
PHP 常用的header头部定义汇总
2015/06/19 PHP
PHP中的Session对象如何使用
2015/09/25 PHP
Yii实现Command任务处理的方法详解
2016/07/14 PHP
Yii2实现自定义独立验证器的方法
2017/05/05 PHP
PHP赋值的内部是如何跑的详解
2019/01/13 PHP
PHP中localeconv()函数的用法
2019/03/26 PHP
设置下载不需要倒计时cookie(倒计时代码)
2008/11/19 Javascript
javascript 面向对象编程 聊聊对象的事
2009/09/17 Javascript
jquery 简短右键菜单 多浏览器兼容
2010/01/01 Javascript
jquery中防刷IP流量软件影响统计的一点对策
2011/07/10 Javascript
jquery.messager.js插件导致页面抖动的解决方法
2013/07/14 Javascript
JavaScript字符串对象toLowerCase方法入门实例(用于把字母转换为小写)
2014/10/17 Javascript
原生Js实现简易烟花爆炸效果的方法
2015/03/20 Javascript
详解javascript遍历方式
2015/11/11 Javascript
简单实现js选项卡切换效果
2016/02/03 Javascript
js当前页面登录注册框,固定div,底层阴影的实例代码
2016/10/04 Javascript
easyui 中的datagrid跨页勾选问题的实现方法
2017/01/18 Javascript
JavaScript实现离开页面前提示功能【附jQuery实现方法】
2017/09/26 jQuery
vue实现多个元素或多个组件之间动画效果
2018/09/25 Javascript
sharp.js安装过程中遇到的问题总结
2020/04/02 Javascript
vue项目,代码提交至码云,iconfont的用法说明
2020/07/30 Javascript
Python命令行参数解析模块optparse使用实例
2015/04/13 Python
python模块简介之有序字典(OrderedDict)
2016/12/01 Python
利用python的socket发送http(s)请求方法示例
2018/05/07 Python
Django框架 querySet功能解析
2019/09/04 Python
keras输出预测值和真实值方式
2020/06/27 Python
详解Python中list[::-1]的几种用法
2020/11/16 Python
详解CSS3 filter:drop-shadow滤镜与box-shadow区别与应用
2020/08/24 HTML / CSS
Bose美国官网:购买Bose耳机和音箱
2019/03/10 全球购物
二年级学生评语大全
2014/04/23 职场文书
语文课外活动总结
2014/08/27 职场文书
CSS中em的正确打开方式详解
2021/04/08 HTML / CSS
关于python爬虫应用urllib库作用分析
2021/09/04 Python