Python實現(xiàn)重建二叉樹的三種方法詳解
本文實例講述了Python實現(xiàn)重建二叉樹的三種方法。分享給大家供大家參考,具體如下:
學(xué)習(xí)算法中,探尋重建二叉樹的方法:
- 用input 前序遍歷順序輸入字符重建
- 前序遍歷順序字符串遞歸解析重建
- 前序遍歷順序字符串堆棧解析重建
如果懶得去看后面的內(nèi)容,可以直接點擊此處本站下載完整實例代碼。
思路
學(xué)習(xí)算法中,python 算法方面的資料相對較少,二叉樹解析重建更少,只能摸著石頭過河。
通過不同方式遍歷二叉樹,可以得出不同節(jié)點的排序。那么,在已知節(jié)點排序的前提下,通過某種遍歷方式,可以將排序進(jìn)行解析,從而構(gòu)建二叉樹。
應(yīng)用上來將,可以用來解析多項式、可以解析網(wǎng)頁、xml等。
本文采用前序遍歷方式的排列,對已知字符串進(jìn)行解析,并生成二叉樹。新手,以解題為目的,暫未優(yōu)化,未能體現(xiàn) Python 簡潔、優(yōu)美。請大牛不吝指正。
首先采用 input 輸入
節(jié)點類
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
以下兩種方法,使用預(yù)先編好的字符串,通過 list 方法轉(zhuǎn)換為 list 傳入進(jìn)行解析
myTree 為實例化一個空樹
調(diào)用遞歸方法重建二叉樹
treeElementList = '124#8##5##369###7##' myTree = myTree.createTreeByListWithRecursion(list(treeElementList)) printBTree(myTree, 0)
遞歸方法重建二叉樹
def createTreeByListWithRecursion(self, preOrderList): """ 根據(jù)前序列表重建二叉樹 :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
調(diào)用堆棧方法重建二叉樹
treeElementList = '124#8##5##369###7##' myTree = myTree.createTreeByListWithStack(list(treeElementList)) printBTree(myTree, 0)
使用堆棧重建二叉樹
def createTreeByListWithStack(self, preOrderList): """ 根據(jù)前序列表重建二叉樹 :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): ''''' 遞歸打印這棵二叉樹,#號表示該節(jié)點為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 輸入及顯示二叉樹結(jié)果
解析字符串的結(jié)果
完整代碼參見:https://github.com/flyhawksz/study-algorithms/blob/master/Class_BinaryTree2.py
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python加密解密算法與技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
利用Fn.py庫在Python中進(jìn)行函數(shù)式編程
這篇文章主要介紹了利用Fn.py庫在Python中進(jìn)行函數(shù)式編程,基于Scala中的類似風(fēng)格,需要的朋友可以參考下2015-04-04Python批量將Word文件轉(zhuǎn)為PDF文件的實現(xiàn)示例
如果想要批量把Word文檔轉(zhuǎn)換為PDF文檔,我們可以使用第三方模塊win32com,本文就來詳細(xì)的介紹一下Python批量將Word文件轉(zhuǎn)為PDF文件的實現(xiàn)示例,感興趣的可以了解一下2023-08-08Python使用asyncio包實現(xiàn)異步編程方式
這篇文章主要介紹了Python使用asyncio包實現(xiàn)異步編程方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06python如何實現(xiàn)排序,并標(biāo)上序號
這篇文章主要介紹了python如何實現(xiàn)排序,并標(biāo)上序號,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06