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中的对象拷贝示例 python引用传递
Jan 23 Python
详解Python2.x中对Unicode编码的使用
Apr 03 Python
centos6.7安装python2.7.11的具体方法
Jan 16 Python
python 设置文件编码格式的实现方法
Dec 21 Python
Python即时网络爬虫项目启动说明详解
Feb 23 Python
python实现从文件中读取数据并绘制成 x y 轴图形的方法
Oct 14 Python
python 二维数组90度旋转的方法
Jan 28 Python
Python os.access()用法实例
Feb 18 Python
pycharm 安装JPype的教程
Aug 08 Python
使用pytorch和torchtext进行文本分类的实例
Jan 08 Python
Pytorch 实现计算分类器准确率(总分类及子分类)
Jan 18 Python
Python 如何对文件目录操作
Jul 10 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
?繁体转换的class
2006/10/09 PHP
php json与xml序列化/反序列化
2013/10/28 PHP
curl实现站外采集的方法和技巧
2014/01/31 PHP
PHP 9 大缓存技术总结
2015/09/17 PHP
CodeIgniter生成静态页的方法
2016/05/17 PHP
php抛出异常与捕捉特定类型的异常详解
2016/10/26 PHP
ThinkPHP开发--使用七牛云储存
2017/09/14 PHP
Laravel项目中timeAgo字段语言转换的改善方法示例
2019/09/16 PHP
Mootools 1.2教程 选项卡效果(Tabs)
2009/09/15 Javascript
文本框获得焦点和失去焦点的判断代码
2012/03/18 Javascript
Tab切换组件(选项卡功能)实例代码
2013/11/21 Javascript
实例代码详解jquery.slides.js
2015/11/16 Javascript
JS在onclientclick里如何控制onclick的执行
2016/05/30 Javascript
利用jQuery对无序列表排序的简单方法
2016/10/16 Javascript
javascript表达式和运算符详解
2017/02/07 Javascript
详解webpack分包及异步加载套路
2017/06/29 Javascript
js学习总结之dom2级事件基础知识详解
2017/07/27 Javascript
微信小程序列表渲染功能之列表下拉刷新及上拉加载的实现方法分析
2017/11/27 Javascript
解决vue attr取不到属性值的问题
2018/09/18 Javascript
JS操作JSON常用方法(10w阅读)
2020/12/06 Javascript
python之yield表达式学习
2014/09/02 Python
在CentOS上配置Nginx+Gunicorn+Python+Flask环境的教程
2016/06/07 Python
python中使用%与.format格式化文本方法解析
2017/12/27 Python
Linux上使用Python统计每天的键盘输入次数
2019/04/17 Python
HTML5实现直播间评论滚动效果的代码
2020/05/27 HTML / CSS
市场开发与营销专业求职信
2013/12/31 职场文书
大学生军训感想
2014/02/16 职场文书
《陶罐和铁罐》教学反思
2014/02/19 职场文书
涉及车辆房产分割的离婚协议书范文
2014/10/12 职场文书
财务整改报告范文
2014/11/05 职场文书
2015年计算机教师工作总结
2015/07/22 职场文书
python迷宫问题深度优先遍历实例
2021/06/20 Python
python基础之类方法和静态方法
2021/10/24 Python
MYSQL 表的全面总结
2021/11/11 MySQL
Python四款GUI图形界面库介绍
2022/06/05 Python
el-table-column 内容不自动换行的解决方法
2022/08/14 Vue.js