Very clean and easy code. Use pickle to solve the problem. I also looked up and tried marshal and json but in python. Those two cannot support new created class object.
import pickle , sys , os class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ return pickle.dumps(root) def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ return pickle.loads(data)