Tree Codec Py
~2 mins read
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
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
def preorder(root):
vals = list()
def go(node):
if node:
vals.append(str(node.val))
go(node.left)
go(node.right)
else:
vals.append("#")
go(root)
return vals
vals = preorder(root)
return " ".join(vals)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
def construct():
val = next(vals)
if val == "#":
return None
node = TreeNode(int(val))
node.left= construct()
node.right= construct()
return node
vals = iter(data.split())
root = construct()
return root