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 获取et和excel的版本号
Apr 09 Python
itchat接口使用示例
Oct 23 Python
Python实现的计数排序算法示例
Nov 29 Python
基于python3 OpenCV3实现静态图片人脸识别
May 25 Python
Python实现合并两个有序链表的方法示例
Jan 31 Python
使用python制作一个为hex文件增加版本号的脚本实例
Jun 12 Python
Python3中的最大整数和最大浮点数实例
Jul 09 Python
使用python实现对元素的长截图功能
Nov 14 Python
python代码xml转txt实例
Mar 10 Python
Python unittest框架操作实例解析
Apr 13 Python
解决Jupyter-notebook不弹出默认浏览器的问题
Mar 30 Python
ROS系统将python包编译为可执行文件的简单步骤
Jul 25 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配置心得包含MYSQL5乱码解决
2006/11/20 PHP
解析func_num_args与func_get_args函数的使用
2013/06/24 PHP
PHP中session跨子域的三种实现方法
2016/07/25 PHP
计算世界完全对称日的js代码,粗糙版
2011/11/04 Javascript
解决window.opener=null;window.close(),只支持IE6不支持IE7,IE8的问题
2014/01/14 Javascript
js点击文本框弹出可选择的checkbox复选框
2016/02/03 Javascript
BootStrap实现手机端轮播图左右滑动事件
2016/10/13 Javascript
jQuery设置和获取select、checkbox、radio的选中值方法
2017/01/01 Javascript
js实现下一页页码效果
2017/03/07 Javascript
vue.js实现条件渲染的实例代码
2017/06/22 Javascript
vue 使用html2canvas将DOM转化为图片的方法
2018/09/11 Javascript
vue实现拖拽的简单案例 不超出可视区域
2019/07/25 Javascript
createObjectURL方法实现本地图片预览
2019/09/30 Javascript
echarts 使用formatter 修改鼠标悬浮事件信息操作
2020/07/20 Javascript
解决ant design vue中树形控件defaultExpandAll设置无效的问题
2020/10/26 Javascript
python的几种开发工具介绍
2007/03/07 Python
Python每天必学之bytes字节
2016/01/28 Python
python字符串连接方法分析
2016/04/12 Python
基于循环神经网络(RNN)实现影评情感分类
2018/03/26 Python
Pytorch抽取网络层的Feature Map(Vgg)实例
2019/08/20 Python
Python爬虫实现的根据分类爬取豆瓣电影信息功能示例
2019/09/15 Python
Python多线程threading join和守护线程setDeamon原理详解
2020/03/18 Python
Python如何使用input函数获取输入
2020/08/06 Python
python中time、datetime模块的使用
2020/12/14 Python
美国鞋类购物网站:Shiekh Shoes
2016/08/21 全球购物
巴黎卡诗加拿大官网:Kérastase加拿大
2018/11/12 全球购物
实习生自我鉴定
2013/12/12 职场文书
大学生旷课检讨书
2014/01/22 职场文书
运动会入场词200字
2014/02/15 职场文书
食品质量与安全专业毕业生求职信
2014/08/11 职场文书
中班上学期个人总结
2015/02/12 职场文书
银行求职自荐信范文
2015/03/04 职场文书
巴黎圣母院读书笔记
2015/06/26 职场文书
2016七夕情人节寄语
2015/12/04 职场文书
导游词之广州陈家祠
2019/10/21 职场文书
Python字符串对齐方法使用(ljust()、rjust()和center())
2021/04/26 Python