-
Notifications
You must be signed in to change notification settings - Fork 0
/
Serialize_and_Deserialize_Binary_Tree.py
53 lines (45 loc) · 1.25 KB
/
Serialize_and_Deserialize_Binary_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
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# ans = deser.deserialize(ser.serialize(root))
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
res = []
def dfs(root):
nonlocal res
if not root:
res.append("N")
return
res.append(str(root.val))
dfs(root.left)
dfs(root.right)
dfs(root)
return ",".join(res)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
tokens = data.split(",")
def dfs():
nonlocal tokens, i
if tokens[i] == "N":
i += 1
return None
node = TreeNode(int(tokens[i]))
i += 1
node.left = dfs()
node.right = dfs()
return node
i = 0
return dfs()