LC.P449[序列化和反序列化二叉搜索树]

方法一:BFS

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
54
55
56
57
58
59
60
/**
* 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) {
if (root == null) return "";
StringBuilder builder = new StringBuilder();
Deque<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
if (cur == null) {
builder.append("#").append(",");
} else {
builder.append(cur.val).append(",");
queue.offer(cur.left);
queue.offer(cur.right);
}
}
return builder.toString();
}

// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data.isEmpty()) return null;
Deque<String> nodes = new LinkedList<>(List.of(data.split(",")));
TreeNode root = new TreeNode(Integer.parseInt(nodes.poll()));
Deque<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
String left = nodes.poll();
String right = nodes.poll();
if (!left.equals("#")) {
cur.left = new TreeNode(Integer.parseInt(left));
queue.offer(cur.left);
}
if (!right.equals("#")) {
cur.right = new TreeNode(Integer.parseInt(right));
queue.offer(cur.right);
}
}
return root;
}
}

// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// String tree = ser.serialize(root);
// TreeNode ans = deser.deserialize(tree);
// return ans;
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$

方法二:先序遍历

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
/**
* 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) {
if (root == null) return "#,";
String left = serialize(root.left);
String right = serialize(root.right);
return root.val + "," + left + right;
}

// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data.isEmpty()) return null;
Deque<String> queue = new LinkedList<>(List.of(data.split(",")));
return buildTree(queue);
}

private TreeNode buildTree(Deque<String> queue) {
String cur = queue.poll();
if (cur.equals("#")) return null;
TreeNode root = new TreeNode(Integer.parseInt(cur));
root.left = buildTree(queue);
root.right = buildTree(queue);
return root;
}
}

// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// String tree = ser.serialize(root);
// TreeNode ans = deser.deserialize(tree);
// return ans;
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$