leetcode-297-Serialize-and-Deserialize-Binary-Tree

描述


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.

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.

Example:

1
2
3
4
5
6
7
8
9
You may serialize the following tree:

1
/ \
2 3
/ \
4 5

as "[1,2,3,null,null,4,5]"

Clarification: The above format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

分析


序列化是指将对象转换成易于传输的格式(一般为字符串),反序列化则为相反操作。这道题要求我们实现二叉搜索树序列化,反序列化,先序遍历二叉树的方式会比较方便,因为先序遍历二叉树得到的数组再转换成二叉树非常直观(想象一下堆的转换)。

在很多情况下,我们用数组来表示二叉树就是因为它们之间用先序遍历的方式非常方便。

解决方案1(Python)


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
# 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, treeList):
if not isinstance(root, TreeNode):
treeList.append(None)
return
treeList.append(root.val)
self._serialize(root.left, treeList)
self._serialize(root.right, treeList)

def serialize(self, root):
"""Encodes a tree to a single string.

:type root: TreeNode
:rtype: str
"""
tree = []
self._serialize(root, tree)
return dumps(tree)

def _deserialize(self, treeList):
if len(treeList) == 0:
return
leftMost = treeList.popleft()
if leftMost is None:
return
root = TreeNode(leftMost)
root.left = self._deserialize(treeList)
root.right = self._deserialize(treeList)
return root

def deserialize(self, data):
"""Decodes your encoded data to tree.

:type data: str
:rtype: TreeNode
"""
treeList = deque(loads(data))
return self._deserialize(treeList)


# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# ans = deser.deserialize(ser.serialize(root))

解决方案1(Java)


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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {

// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
tree2String(root, sb);
return sb.toString();
}

private void tree2String(TreeNode node, StringBuilder sb) {
if (node == null) {
sb.append("#").append(" ");
return;
}
sb.append(node.val).append(" ");
tree2String(node.left, sb);
tree2String(node.right, sb);

}

// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
Deque<String> nodes = new LinkedList<>();
nodes.addAll(Arrays.asList(data.split(" ")));
return string2Tree(nodes);
}

private TreeNode string2Tree(Deque<String> nodes) {
String val = nodes.remove();
if (val.equals("#")) {
return null;
}
TreeNode node = new TreeNode(Integer.valueOf(val));
node.left = string2Tree(nodes);
node.right = string2Tree(nodes);
return node;
}
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

相关问题


题目来源