-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path297.serialize_and_serialize_binary_tree.py
More file actions
72 lines (63 loc) · 2.08 KB
/
Copy path297.serialize_and_serialize_binary_tree.py
File metadata and controls
72 lines (63 loc) · 2.08 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
from collections import deque
# 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
"""
result = []
stack = deque([root])
while stack:
new_stack = deque()
while stack:
node = stack.popleft()
if node is None:
result.append(None)
else:
new_stack.append(node.left)
new_stack.append(node.right)
result.append(node.val)
if not any(new_stack):
break
stack = new_stack
return ','.join(str(x) if x is not None else 'x' for x in result)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
data = deque(int(x) if x != 'x' else None for x in data.split(','))
if not data:
return None
root_data = data.popleft()
if root_data is None:
return None
root = TreeNode(root_data)
parents = [root]
while data:
new_parents = []
for parent in parents:
if parent is None:
continue
left = data.popleft()
right = data.popleft()
if left is not None:
left = TreeNode(left)
if right is not None:
right = TreeNode(right)
new_parents.append(left)
new_parents.append(right)
parent.left = left
parent.right = right
parents = new_parents
return root
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))