首页 > 编程 > Python > 正文

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

2020-02-15 22:00:31
字体:
来源:转载
供稿:网友

本文实例讲述了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            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表