Google
297 Serialize and Deserialize Binary Tree

1. Question

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.
For example, you may serialize the following tree
1
1
2
/ \
3
2 3
4
/ \
5
4 5
Copied!
as"[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

2. Implementation

1
/**
2
* Definition for a binary tree node.
3
* public class TreeNode {
4
* int val;
5
* TreeNode left;
6
* TreeNode right;
7
* TreeNode(int x) { val = x; }
8
* }
9
*/
10
public class Codec {
11
12
// Encodes a tree to a single string.
13
public String serialize(TreeNode root) {
14
StringBuilder res = new StringBuilder();
15
convertToString(root, res);
16
return res.toString();
17
}
18
19
public void convertToString(TreeNode node, StringBuilder res) {
20
if (node == null) {
21
res.append("#").append(",");
22
}
23
else {
24
res.append(node.val).append(",");
25
convertToString(node.left, res);
26
convertToString(node.right, res);
27
}
28
}
29
30
// Decodes your encoded data to tree.
31
public TreeNode deserialize(String data) {
32
Queue<String> queue = new LinkedList<>();
33
queue.addAll(Arrays.asList(data.split(",")));
34
return buildTree(queue);
35
}
36
37
public TreeNode buildTree(Queue<String> queue) {
38
String val = queue.remove();
39
if (val.equals("#")) {
40
return null;
41
}
42
TreeNode node = new TreeNode(Integer.valueOf(val));
43
node.left = buildTree(queue);
44
node.right = buildTree(queue);
45
return node;
46
}
47
}
48
49
// Your Codec object will be instantiated and called as such:
50
// Codec codec = new Codec();
51
// codec.deserialize(codec.serialize(root));
Copied!

3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(n)