forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserialize-and-deserialize-n-ary-tree.py
65 lines (50 loc) · 1.48 KB
/
serialize-and-deserialize-n-ary-tree.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# Time: O(n)
# Space: O(h)
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
class Codec(object):
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: Node
:rtype: str
"""
def dfs(node, vals):
if not node:
return
vals.append(str(node.val))
for child in node.children:
dfs(child, vals)
vals.append("#")
vals = []
dfs(root, vals)
return " ".join(vals)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: Node
"""
def isplit(source, sep):
sepsize = len(sep)
start = 0
while True:
idx = source.find(sep, start)
if idx == -1:
yield source[start:]
return
yield source[start:idx]
start = idx + sepsize
def dfs(vals):
val = next(vals)
if val == "#":
return None
root = Node(int(val), [])
child = dfs(vals)
while child:
root.children.append(child)
child = dfs(vals)
return root
if not data:
return None
return dfs(iter(isplit(data, ' ')))