serialize and deserialize binary tree

Go Back home

Credit: S. Pochmann

 1 class Codec:
 2 
 3     def serialize(self, root):
 4         def doit(node):
 5             if node:
 6                 vals.append(str(node.val))
 7                 doit(node.left)
 8                 doit(node.right)
 9             else:
10                 vals.append('#')
11         vals = []
12         doit(root)
13         return ' '.join(vals)
14 
15     def deserialize(self, data):
16         def doit():
17             val = next(vals)
18             if val == '#':
19                 return None
20             node = TreeNode(int(val))
21             node.left = doit()
22             node.right = doit()
23             return node
24         vals = iter(data.split())
25         return doit()