You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
3
+
4
+
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
5
+
6
+
Example:
7
+
8
+
You may serialize the following tree:
9
+
10
+
1
11
+
/ \
12
+
2 3
13
+
/ \
14
+
4 5
15
+
16
+
as "[1,2,3,null,null,4,5]"
17
+
'''
18
+
19
+
# Definition for a binary tree node.
20
+
# class TreeNode(object):
21
+
# def __init__(self, x):
22
+
# self.val = x
23
+
# self.left = None
24
+
# self.right = None
25
+
26
+
classCodec:
27
+
28
+
defserialize(self, root):
29
+
"""Encodes a tree to a single string.
30
+
31
+
:type root: TreeNode
32
+
:rtype: str
33
+
"""
34
+
35
+
defpreorder(root):
36
+
ifroot:
37
+
seralizeTree.append(str(root.val) +',')
38
+
preorder(root.left)
39
+
preorder(root.right)
40
+
else:
41
+
seralizeTree.append('#,')
42
+
43
+
seralizeTree= []
44
+
preorder(root)
45
+
return''.join(seralizeTree)
46
+
47
+
48
+
defdeserialize(self, data):
49
+
"""Decodes your encoded data to tree.
50
+
51
+
:type data: str
52
+
:rtype: TreeNode
53
+
"""
54
+
55
+
defbuildTree(preorder):
56
+
value=preorder.pop(0)
57
+
ifvalue=='#':
58
+
returnNone
59
+
60
+
node=TreeNode(int(value))
61
+
node.left=buildTree(preorder)
62
+
node.right=buildTree(preorder)
63
+
returnnode
64
+
65
+
preorder=data.split(',')[:-1]
66
+
returnbuildTree(preorder)
67
+
68
+
69
+
# Your Codec object will be instantiated and called as such:
0 commit comments