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

重建二叉树 python_Python实现重建二叉树的三种方法详解本文实例讲述了Python实现重建二叉树的三种方法。分享给大家供大家参考,具体如下:学习算法中,探寻重建二叉树的方法:用input前序遍历顺序输入字符重建前序遍历顺序字符串递归解析重建前序遍历顺序字符串堆栈解析重建如果懒得去看后面的内容,可以直接点击此处本站下载完整实例代码。思路学习算法中,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 输入及显示二叉树结果

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

解析字符串的结果

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

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

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

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

本文标题: Python实现重建二叉树的三种方法详解

本文地址: http://www.cppcns.com/jiaoben/python/230990.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/132283.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • react对象控制台输出 null 的问题

    react对象控制台输出 null 的问题

    2021年7月2日
    87
  • Rpc接口压测_rpc服务接口测试

    Rpc接口压测_rpc服务接口测试前言哈喽,喜欢这篇文章的话烦请点个赞哦!万分感谢(^▽^)PS:有问题可以联系我们哦vceshiren001复制“下方链接”,提升测试核心竞争力!更多技术文章分享和免费资料领取现今有比较多的rpc框架应用于实际的生产中,像比较流行的Dubbo、Motan、Thrift、Grpc等。今天作者将以最近项目中用到的grpc为例,结合jmeter来介绍下rpc压测实施步骤。学习本文前需对rpc框架、jmeter有个大致的了解,知道rpc如何用工具生成各种语言的代码。Grpc本身是支持很多种语言的,而jm

    2022年10月13日
    4
  • android 定时器重置,Android定时器延迟和重置[通俗易懂]

    android 定时器重置,Android定时器延迟和重置[通俗易懂]我确定在这里的某处有类似的问题,但我似乎无法找到它。Android定时器延迟和重置这是我正在尝试做的。假设我已连接到服务器,并且如果在过去5分钟内没有用户拨打任何电话,我想断开连接。但是,如果连一个单一的呼叫时,5分钟计时器将复位,倒计时5将重新开始..它似乎很简单,但我是一种新的Android和试图搞清楚这些事情..在此先感谢!=======编辑所以这里的什么我想要做的代码的例子。try{cl…

    2022年7月25日
    18
  • 学习微机原理与接口这一篇就够了

    学习微机原理与接口这一篇就够了注意问题:由于这篇文章我是用WORD编辑的,写完以后,发现没办法转换为MD格式,所以我只能用截图的形式上传了,写这篇文章的主要目的是对微机原理与接口基础知识的一个简单梳理。…

    2022年10月2日
    4
  • Idea激活码永久有效Idea2021.2.2激活码教程-持续更新,一步到位[通俗易懂]

    Idea激活码永久有效Idea2021.2.2激活码教程-持续更新,一步到位[通俗易懂]Idea激活码永久有效2021.2.2激活码教程-Windows版永久激活-持续更新,Idea激活码2021.2.2成功激活

    2022年6月17日
    295
  • 这11款chrome神器,用起来爽到爆

    这11款chrome神器,用起来爽到爆前言对于从事IT行业的我们来说,几乎无时无刻都在用chrome浏览器,因为它给我们的工作和生活带来了极大的便利。今天给大家分享我用过的11款牛逼的chrome插件,你看完前3个可能就会忍不住想点赞了。1.谷歌翻译很多小伙伴,英语不太好,包括我自己,英语刚过四级。从事软件相关工作时,有时有些吃力,因为很多优秀的技术网站、书籍或者文章都是老外写的,如果因为看不懂就放弃阅读,我们将会少了很多学习和进步的机会。今天分享的第一个神器就是:谷歌翻译。在没使用谷歌翻译之前,访问https://doc

    2022年5月6日
    53

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号