Serialization is the process of converting a data structure or object to a sequence of bits so then it can be stored in A file or memory buffer, or transmitted across a network connection link to being reconstructed later in the same or another Computer environment.
Design a algorithm to serialize and deserialize a binary tree. There is no restriction on what your serialization/deserialization algorithm should work. You just need to ensure, a binary tree can is serialized to a string and this string can is deserialized to the origin AL tree structure.
Example:
Serialize the following tree: 1 / 2 3 / 4 "[1,2,3,null,null,4,5]"
Clarification:the above format is the same as how leetcode serializes a binary tree. You don't necessarily need to follow the this format, so that you are creative and come up with different approaches yourself.
Note:do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
Serializes and deserializes binary trees. The solution is mainly two kinds of sequence traversal and pre-sequence traversal.
The pre-order traversal is basically recursive, and you need to save a global variable to tell the code, which is now working with the number of the array. More trouble.
So here's the code for the sequence traversal:
classCodec:defserialize (self, root):"""encodes a tree to a single string. : Type Root:TreeNode:rtype:str""" ifRoot isNone:return ""Res=[] Queue=Collections.deque () queue.append (root) whileQueue:node=Queue.popleft ()ifnode:res.append (str (node.val)) queue.append (Node.left) queue.append (nod E.right)Else: Res.append ('#') return ",". Join (RES)defDeserialize (self, data):"""decodes your encoded data to tree. : Type Data:str:rtype:TreeNode""" ifdata = ="": returnNone Res= Data.split (',') Queue=collections.deque () root=TreeNode (res[0]) I= 1queue.append (Root) whileQueue:cur=queue.popleft () leftval=Res[i]ifLeftval! ='#': Left=TreeNode (int (leftval)) Cur.left=Left queue.append i+ = 1Rightval=Res[i]ifRightval! ='#': Right=TreeNode (int (rightval)) Cur.right=Right queue.append i+ = 1returnRoot
Note that the wording here is for[1,2,3,null,null,4,5]的序列化结果为“1,2,3,#,#,4,5,#,#,#,#”
Also note that the deserialization here actually utilizes the information of the first layer only the root node, so it is placed in the queue first.
Serialize and deserialize Binary Tree