今天就跟大家聊聊有關(guān)怎么在Python中實(shí)現(xiàn)一個(gè)序列化和反序列化的二叉樹算法,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
創(chuàng)新互聯(lián)建站是一家集網(wǎng)站建設(shè),科爾沁左翼企業(yè)網(wǎng)站建設(shè),科爾沁左翼品牌網(wǎng)站建設(shè),網(wǎng)站定制,科爾沁左翼網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,科爾沁左翼網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。序列化二叉樹
先序遍歷二叉樹
def recursionSerialize(self, root): series = '' if root == None: series += ',$' else: series += (',' + str(root.val)) series += self.recursionSerialize(root.left) series += self.recursionSerialize(root.right) return series def Serialize(self, root): return self.recursionSerialize(root)[1:]
結(jié)果:
root = TreeNode(11) root.left = TreeNode(2) root.right = TreeNode(3) series = Solution().Serialize(root) print(series) >>>11,2,$,$,3,$,$
反序列化
先構(gòu)建根節(jié)點(diǎn),然后左節(jié)點(diǎn),右節(jié)點(diǎn),同樣是遞歸
注意由于使用的是字符串的表示形式,可以先轉(zhuǎn)化為list,
print(series.split(',')) >>>['11', '2', '$', '$', '3', '$', '$']
然后再處理就不需要將大于10的數(shù)字轉(zhuǎn)換過來了:
def getValue(self, s, sIndex): #處理超過10的數(shù)字,將數(shù)字字符轉(zhuǎn)變?yōu)閿?shù)字 val = 0 while ord(s[sIndex]) <= ord('9') and ord(s[sIndex]) >= ord('0'): val = val * 10 + int(s[sIndex]) sIndex += 1 return val, sIndex - 1
下面是反序列化的遞歸函數(shù):
def Deserialize(self, s): if self.sIndex < len(s): if s[self.sIndex] == ',': self.sIndex += 1 if s[self.sIndex] == '$': return None val, self.sIndex = self.getValue(s, self.sIndex) treeNode = TreeNode(val) self.sIndex += 1 treeNode.left = self.Deserialize(s) self.sIndex += 1 treeNode.right = self.Deserialize(s) return treeNode
完整解法
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.sIndex = 0 def recursionSerialize(self, root): series = '' if root == None: series += ',$' else: series += (',' + str(root.val)) series += self.recursionSerialize(root.left) series += self.recursionSerialize(root.right) return series def Serialize(self, root): return self.recursionSerialize(root)[1:] def getValue(self, s, sIndex): #處理超過10的數(shù)字,將數(shù)字字符轉(zhuǎn)變?yōu)閿?shù)字 val = 0 while ord(s[sIndex]) <= ord('9') and ord(s[sIndex]) >= ord('0'): val = val * 10 + int(s[sIndex]) sIndex += 1 return val, sIndex - 1 def Deserialize(self, s): if self.sIndex < len(s): if s[self.sIndex] == ',': self.sIndex += 1 if s[self.sIndex] == '$': return None val, self.sIndex = self.getValue(s, self.sIndex) treeNode = TreeNode(val) self.sIndex += 1 treeNode.left = self.Deserialize(s) self.sIndex += 1 treeNode.right = self.Deserialize(s) return treeNode
看完上述內(nèi)容,你們對怎么在Python中實(shí)現(xiàn)一個(gè)序列化和反序列化的二叉樹算法有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。