樹(7)-----二叉樹的序列化和反序列化
阿新 • • 發佈:2018-07-01
層次 not oot return end else none In bsp
1、序列化:層次遍歷【用字符串來存儲】
2、反序列化:用隊列存已經建立的節點,從序列化後的字符串列表取數來建立樹
def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if not root: return "" prev,strres=[root],"" while prev: cur=[] while prev: node=prev.pop(0) if node: strres+=str(node.val)+‘,‘ cur.append(node.left) cur.append(node.right) else: strres+=‘#‘+‘,‘ prev=curreturn strres[:-1] def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if not data: return None listdata=data.split(‘,‘) root=TreeNode(listdata[0]) queue=[root] i=0 while queue: node=queue.pop(0) if listdata[i+1]!=‘#‘: node.left=TreeNode(listdata[i+1]) queue.append(node.left) i+=1 if listdata[i+1]!=‘#‘: node.right=TreeNode(listdata[i+1]) queue.append(node.right) i+=1 return root
樹(7)-----二叉樹的序列化和反序列化