-
Notifications
You must be signed in to change notification settings - Fork 2
/
sol.py
70 lines (52 loc) · 1.64 KB
/
sol.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
64
65
66
67
68
69
70
from typing import List
# 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):
arr = []
if not root:
return ""
nodes = [(root, 1)]
while nodes:
node, idx = nodes.pop(0)
if not node:
arr.append(None)
continue
arr.append((node, idx))
nodes.append((node.left, idx * 2))
nodes.append((node.right, idx * 2 + 1))
res = []
for item in arr:
if item is None:
continue
res.append(f"{item[1]}*{item[0].val}")
raw = "_".join(res)
return raw
def deserialize(self, data):
if data == "":
return None
itemsraw = data.split("_")
data = list(map(lambda x: x.split("*"), itemsraw))
mapped = {}
for idx, item in data:
mapped[idx] = item
def build(idx):
if not mapped.keys():
return None
if str(idx) not in mapped:
return None
cur = TreeNode(int(mapped[str(idx)]))
del mapped[str(idx)]
left = build(idx * 2)
right = build(idx * 2 + 1)
cur.left = left
cur.right = right
return cur
return build(1)
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))