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列表操作使用示例分享
Feb 21 Python
python字符串替换示例
Apr 24 Python
Python远程桌面协议RDPY安装使用介绍
Apr 15 Python
浅述python2与python3的简单区别
Sep 19 Python
解决Shell执行python文件,传参空格引起的问题
Oct 30 Python
python3的print()函数的用法图文讲解
Jul 16 Python
python实现桌面气泡提示功能
Jul 29 Python
手把手教你进行Python虚拟环境配置教程
Feb 03 Python
Python实现手绘图效果实例分享
Jul 22 Python
Python持续监听文件变化代码实例
Jul 22 Python
python获取命令行参数实例方法讲解
Nov 02 Python
Python爬虫入门案例之回车桌面壁纸网美女图片采集
Oct 16 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中var_export与var_dump的区别分析
2010/08/21 PHP
php中常用的预定义变量小结
2012/05/09 PHP
PHP数组排序之sort、asort与ksort用法实例
2014/09/08 PHP
thinkPHP中配置的读取与C方法详解
2016/12/05 PHP
PHP排序算法之直接插入排序(Straight Insertion Sort)实例分析
2018/04/20 PHP
PHP实现Huffman编码/解码的示例代码
2018/04/20 PHP
PHP设计模式(八)装饰器模式Decorator实例详解【结构型】
2020/05/02 PHP
写出高效jquery代码的19条指南
2014/03/19 Javascript
javascript基于DOM实现权限选择实例分析
2015/05/14 Javascript
AngularJS数据源的多种获取方式汇总
2016/02/02 Javascript
理解javascript对象继承
2016/04/17 Javascript
详解Vue 普通对象数据更新与 file 对象数据更新
2017/04/26 Javascript
微信小程序 自定义Toast实例代码
2017/06/12 Javascript
浅谈angularJs函数的使用方法(大小写转换,拷贝,扩充对象)
2018/10/08 Javascript
Easyui 去除jquery-easui tab页div自带滚动条的方法
2019/05/10 jQuery
在Vue中使用icon 字体图标的方法
2019/06/14 Javascript
详解vue中多个有顺序要求的异步操作处理
2019/10/29 Javascript
微信小程序使用GoEasy实现websocket实时通讯
2020/05/19 Javascript
Node在Controller层进行数据校验的过程详解
2020/08/28 Javascript
ES6的循环与可迭代对象示例详解
2021/01/31 Javascript
[10:04]国际邀请赛采访专栏:DK.Farseer,mouz.Black^,采访员Josh专访
2013/08/05 DOTA
[01:35]2014DOTA2西雅图邀请赛 专访狐狸妈青春献给刀塔
2014/07/08 DOTA
[52:52]DOTA2上海特级锦标赛C组资格赛#1 OG VS LGD第三局
2016/02/27 DOTA
[12:29]2018国际邀请赛 开幕秀
2018/08/22 DOTA
Python语言技巧之三元运算符使用介绍
2013/03/04 Python
python daemon守护进程实现
2016/08/27 Python
python opencv设置摄像头分辨率以及各个参数的方法
2018/04/02 Python
python selenium操作cookie的实现
2020/03/18 Python
python网络编程:socketserver的基本使用方法实例分析
2020/04/09 Python
估算杭州有多少软件工程师
2015/08/11 面试题
教师自我鉴定
2013/12/13 职场文书
2014年单位植树节活动方案
2014/03/23 职场文书
教育合作协议范本
2014/10/17 职场文书
2015年学校财务工作总结
2015/05/19 职场文书
会计岗位工作总结
2015/08/12 职场文书
2016年三八红旗手先进事迹材料
2016/02/26 职场文书