请实现两个函数来序列化和反序列化二叉树。示例:可以将如下二叉树:1/\23/\45序列化为“[1,2,3,null,null,4,5]”注:本主题与主站297主题相同:https://leetcode-cn.com/probl...思路BFS代码Python3#定义一个二叉树节点.#classTreeNode(object):#def__init__(self,x):#self.val=x#self.left=None#self.right=NoneclassCodec:defserialize(self,root):"""Encodesatreetoasinglestring.:typeroot:TreeNode:rtype:str"""importcollectionsifnotroot:返回"[]"queue=collections.deque()queue.append(root)res=[]#层序遍历BFSwhilequeue:node=queue.popleft()ifnode:res.append(str(node.val))queue.append(node.left)queue.append(node.right)else:res.append("null")return"["+",".join(res)+"]"defdeserialize(self,data):"""将编码后的数据解码为树。:typedata:str:rtype:TreeNode"""importcollectionsifdata=="[]":return#去掉左右括号,slice根据逗号vals,i=data[1:-1].split(","),1root=TreeNode(int(vals[0]))queue=collections.deque()queue.append(root)whilequeue:node=queue.popleft()#构建左子树ifvals[i]!="null":node.left=TreeNode(int(vals[i]))queue.append(node.left)i+=1#构建右子树ifvals[i]!="null":node.right=TreeNode(int(vals[i]))queue.append(node.right)i+=1returnroot#你的Codec对象将被实例化并这样调用:#codec=Codec()#codec.deserialize(codec.serialize(root))链接GitHub面试题37.序列化二叉树(顺序遍历BFS,清晰图)
