-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserialize_and_deserialize_binary_tree.py
More file actions
47 lines (37 loc) · 1.18 KB
/
Copy pathserialize_and_deserialize_binary_tree.py
File metadata and controls
47 lines (37 loc) · 1.18 KB
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
from collections import deque
from src.common import TreeNode
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string."""
if not root:
return "null"
queue = deque([root])
result = []
while queue:
node = queue.popleft()
if node:
result.append(str(node.val))
queue.append(node.left)
queue.append(node.right)
else:
result.append("null")
return ",".join(result)
def deserialize(self, data):
"""Decodes your encoded data to tree."""
if data == "null":
return None
values = data.split(",")
root = TreeNode(int(values[0]))
queue = deque([root])
index = 1
while queue:
node = queue.popleft()
if values[index] != "null":
node.left = TreeNode(int(values[index]))
queue.append(node.left)
index += 1
if values[index] != "null":
node.right = TreeNode(int(values[index]))
queue.append(node.right)
index += 1
return root