0%

leetCode-297:Serialize and Deserialize Binary Tree

问题解法

给定一个二叉树,要求将树进行序列化和反序列化。题目链接:**点我**

样例输入输出

输入:[1,2,3]

输出:[1,2,3]

说明:表示树

1

/ \

2 3

输入:[]

输出:[]

问题解法

参考 LeetCode 里对二叉树的表现方式,使用广度优先搜索算法对树进行序列化和反序列化。在序列化过程总,遇到节点是叶子节点时,需要将其左右孩子表示为 NULL 进行输出,以方便后续的反序列化操作。

在进行反序列化过程中,每次读取同一层级的节点进行处理 ,这样可以保证让数组的指针依次移动。由于每个节点的左右孩子都是在相邻的,所以在处理节点时可以顺序读取。

代码如下

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {

private static final String NULL = "NULL";

private static final String SEPARATOR = ",";

// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node == null) {
sb.append(SEPARATOR).append(NULL);
} else {
sb.append(SEPARATOR).append(node.val);
queue.add(node.left);
queue.add(node.right);
}
}

if (sb.length() > 1) {
sb = sb.deleteCharAt(0);
}
return sb.toString();
}

// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] strs = data.split(SEPARATOR);
if (strs.length == 0 || strs[0].equals(NULL)) {
return null;
}

int index = 1;
TreeNode root = new TreeNode(Integer.parseInt(strs[0]));
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int count = queue.size();
for (int i = count; i > 0; i--) {
TreeNode current = queue.poll();
if (!strs[index].equals(NULL)) {
TreeNode left = new TreeNode(Integer.parseInt(strs[index]));
current.left = left;
queue.add(left);
}
if (!strs[index + 1].equals(NULL)) {
TreeNode right = new TreeNode(Integer.parseInt(strs[index + 1]));
current.right = right;
queue.add(right);
}
index += 2;
}
}

return root;
}
}

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