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=cur return 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
原文地址:https://www.cnblogs.com/Lee-yl/p/9250242.html
时间: 2024-10-08 10:02:03