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 相关文章推荐
详解使用 pyenv 管理多个版本 python 环境
Oct 19 Python
浅谈numpy库的常用基本操作方法
Jan 09 Python
python绘制中国大陆人口热力图
Nov 07 Python
python抖音表白程序源代码
Apr 07 Python
Pandas之排序函数sort_values()的实现
Jul 09 Python
Django Rest framework认证组件详细用法
Jul 25 Python
Python urlencode和unquote函数使用实例解析
Mar 31 Python
查看已安装tensorflow版本的方法示例
Apr 19 Python
python中tab键是什么意思
Jun 18 Python
浅谈Python中的继承
Jun 19 Python
Selenium webdriver添加cookie实现过程详解
Aug 12 Python
python3列表删除大量重复元素remove()方法的问题详解
Jan 04 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
初探PHP5
2006/10/09 PHP
PHP去除数组中重复的元素并按键名排序函数
2008/08/18 PHP
cmd下运行php脚本
2008/11/25 PHP
php 读取文件乱码问题
2010/02/20 PHP
基于php中使用excel的简单介绍
2013/08/02 PHP
PHP6新特性分析
2016/03/03 PHP
PHP操作mysql数据库分表的方法
2016/06/09 PHP
PHP实现小程序批量通知推送
2018/11/27 PHP
js实现改进的仿蓝色论坛导航菜单效果代码
2015/09/06 Javascript
利用jquery制作滚动到指定位置触发动画
2016/03/26 Javascript
非常棒的jQuery图片轮播效果
2016/04/17 Javascript
浅析jquery数组删除指定元素的方法:grep()
2016/05/19 Javascript
url传递的参数值中包含&amp;时,url自动截断问题的解决方法
2016/08/02 Javascript
javascript事件捕获机制【深入分析IE和DOM中的事件模型】
2016/12/15 Javascript
微信小程序实现图片预加载组件
2017/01/18 Javascript
JS变量及其作用域
2017/03/29 Javascript
vue源码nextTick使用及原理解析
2019/08/13 Javascript
jquery实现的分页显示功能示例
2019/08/23 jQuery
layui radio点击事件实现input显示和隐藏的例子
2019/09/02 Javascript
在Angular中实现一个级联效果的下拉框的示例代码
2020/05/20 Javascript
Python实现带参数与不带参数的多重继承示例
2018/01/30 Python
python 实现在无序数组中找到中位数方法
2020/03/03 Python
Python super()函数使用及多重继承
2020/05/06 Python
详解Pycharm第三方库的安装及使用方法
2020/12/29 Python
python利用opencv实现颜色检测
2021/02/23 Python
党员干部廉洁承诺书
2014/05/28 职场文书
今冬明春火灾防控工作方案
2014/05/29 职场文书
社会工作专业自荐信
2014/09/26 职场文书
房产公证书格式
2015/01/26 职场文书
争先创优个人总结
2015/03/04 职场文书
2015企业年终工作总结范文
2015/05/27 职场文书
论文答辩开场白大全
2015/05/27 职场文书
2015新教师教学工作总结
2015/07/22 职场文书
大学生创业,为什么都会选择快餐饮?
2019/08/08 职场文书
redis 限制内存使用大小的实现
2021/05/08 Redis
Python编程根据字典列表相同键的值进行合并
2021/10/05 Python