Serialize and Deserialize Binary Tree

Serialize and Deserialize Binary Tree

Recursive Preorder Version - 120ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
vals = []
def convert(node):
if node:
vals.append(str(node.val))
convert(node.left)
convert(node.right)
else:
vals.append('#')
convert(root)
return ' '.join(vals)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
def convert():
val = next(vals)
if val == '#':
return None
node = TreeNode(int(val))
node.left = convert()
node.right = convert()
return node
vals = iter(data.split())
return convert()
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))

leet code