-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path297. Serialize and Deserialize Binary Tree.py
More file actions
45 lines (42 loc) · 1.22 KB
/
297. Serialize and Deserialize Binary Tree.py
File metadata and controls
45 lines (42 loc) · 1.22 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
import collections
class TreeNode(object):
""" Definition of a binary tree node."""
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# serialization
class Codec:
def serialize(self,root):
def rserialize(root, string):
if not root:
string += 'None,'
else:
string += str(root.val) +','
string = rserialize(root.left, string)
string = rserialize(root.right, string)
return string
return rserialize(root, '')
# serialization
def serialize(self, root):
def dfs(root):
if not root:
res.append("None")
return
res.append(str(root.val))
dfs(root.left)
dfs(root.right)
res = []
dfs(root)
return ','.join(res)
def deserialize(self, data):
def dfs(text) -> TreeNode:
val = text.popleft()
if val == 'None':
return None
root = TreeNode(val)
root.left = dfs(text)
root.right = dfs(text)
return root
text = collections.deque(data.split(','))
return dfs(next)