Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called ‘serialization’ and reading back from the file to reconstruct the exact same binary tree is ‘deserialization’.
There is no limit of how you deserialize or serialize a binary tree, you only need to make sure you can serialize a binary tree to a string and deserialize this string to the original structure.
Example
An example of testdata: Binary tree {3,9,20,#,#,15,7}, denote the following structure:
12345
3
/ \
9 20
/ \
15 7
Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.
You can use other method to do serializaiton and deserialization.
Solution
Time: O(n)
Use pre-order to implement it
when you do de-serialization, remember to pop the list.
"""Definition of TreeNode:class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None"""classSolution:''' @param root: An object of TreeNode, denote the root of the binary tree. This method will be invoked first, you should design your own algorithm to serialize a binary tree which denote by a root node to a string which can be easily deserialized by your own "deserialize" method later. '''defserialize_helper(self,root,ret):ret.append(root.val)ifroot.left!=None:self.serialize_helper(root.left,ret)else:ret.append('#')ifroot.right!=None:self.serialize_helper(root.right,ret)else:ret.append('#')returnretdefserialize(self,root):# write your code hereret=[]ifroot==None:returnretself.serialize_helper(root,ret)returnret''' @param data: A string serialized by your serialize method. This method will be invoked second, the argument data is what exactly you serialized at method "serialize", that means the data is not given by system, it's given by your own serialize method. So the format of data is designed by yourself, and deserialize it here as you serialize it in "serialize" method. '''defdeserialize_helper(self,data):ifdata==None:returnNoneifdata[0]=='#':data.pop(0)returnNoneNode=TreeNode(data[0])data.pop(0)Node.left=self.deserialize_helper(data)Node.right=self.deserialize_helper(data)returnNodedefdeserialize(self,data):# write your code hereifdata==Noneorlen(data)==0:returnNonereturnself.deserialize_helper(data)