Python实现重建二叉树的三种方法详解

 更新时间:2018年06月23日 01:58:51   作者:fly_hawk  
这篇文章主要介绍了Python实现重建二叉树的三种方法,结合实例形式分析了Python重建二叉树的实现方法、操作技巧与注意事项,需要的朋友可以参考下

本文实例讲述了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 输入及显示二叉树结果

 

解析字符串的结果

 

完整代码参见:https://github.com/flyhawksz/study-algorithms/blob/master/Class_BinaryTree2.py

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

  • 详解Django自定义图片和文件上传路径(upload_to)的2种方式

    详解Django自定义图片和文件上传路径(upload_to)的2种方式

    这篇文章主要介绍了详解Django自定义图片和文件上传路径(upload_to)的2种方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • python socket模块创建和使用套接字示例详解

    python socket模块创建和使用套接字示例详解

    这篇文章主要为大家介绍了python socket模块来创建和使用套接字示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-06-06
  • Python如何筛选序列中的元素的方法实现

    Python如何筛选序列中的元素的方法实现

    这篇文章主要介绍了Python如何筛选序列中的元素的方法实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-07-07
  • Python3.5 Pandas模块缺失值处理和层次索引实例详解

    Python3.5 Pandas模块缺失值处理和层次索引实例详解

    这篇文章主要介绍了Python3.5 Pandas模块缺失值处理和层次索引,结合实例形式详细分析了Python3.5 Pandas模块缺失值处理和层次索引的原理、处理方法及相关操作注意事项,需要的朋友可以参考下
    2019-04-04
  • 超级好用的4个Python命令行可视化库

    超级好用的4个Python命令行可视化库

    通常大家都是在自己的电脑上跑程序,直接是可以可视化相应的结果.如果是在服务器上的话,使用终端,是不太方便查看结果. 今天,小F就给大家介绍4个可以在命令行中使用的Python库. 分别是Bashplotlib、tqdm、PrettyTable、Colorama,需要的朋友可以参考下
    2021-06-06
  • Python pip安装第三方库的攻略分享

    Python pip安装第三方库的攻略分享

    pip 就是 Python 标准库(The Python Standard Library)中的一个包,只是这个包比较特殊,用它可以来管理 Python 标准库(The Python Standard Library)中其他的包。本文为大家介绍了pip安装第三方库的方法,需要的可以参考一下
    2022-11-11
  • Python实现绘制凸包的示例代码

    Python实现绘制凸包的示例代码

    凸包(Convex Hull)是一个计算几何(图形学)中的概念。这篇文章主要为大家详细介绍了Python绘制凸包的示例代码,感兴趣的小伙伴可以了解一下
    2023-05-05
  • Python pandas 重命名索引和列名称的实现

    Python pandas 重命名索引和列名称的实现

    本文主要介绍了Python pandas 重命名索引和列名称的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • selenium+python实现基本自动化测试的示例代码

    selenium+python实现基本自动化测试的示例代码

    这篇文章主要介绍了selenium+python实现基本自动化测试的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • 跟老齐学Python之画圈还不简单吗?

    跟老齐学Python之画圈还不简单吗?

    画圈?换一个说法就是循环。循环,是高级语言编程中重要的工作。现实生活中,很多事情都是在循环,日月更迭,斗转星移,无不是循环;王朝更迭,寻常百姓,也都是循环。
    2014-09-09

最新评论