二叉树的序列化和反序列化
- 队列中 add 和 offer 方法的区别:两者都是往队列尾部插入元素,不同的是,当超出队列界限的时候,add()方法是抛出异常让你处理,而 offer()方法是直接返回false
import java.util.LinkedList;
import java.util.Queue;
public class Code_04_Serialize {
public static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public static String Serialize(TreeNode root) {
if (root == null) {
return "#!";
}
String res = root.val + "!";
res += Serialize(root.left);
res += Serialize(root.right);
return res;
}
public static TreeNode Deserialize(String str) {
String[] values = str.split("!");
Queue<String> queue = new LinkedList<>();
for (int i = 0; i != values.length; i++) {
queue.offer(values[i]);
}
return reconPreOrder(queue);
}
public static TreeNode reconPreOrder(Queue<String> queue) {
String value = queue.poll();
if (value.equals("#")) {
return null;
}
TreeNode head = new TreeNode(Integer.valueOf(value));
head.left = reconPreOrder(queue);
head.right = reconPreOrder(queue);
return head;
}
}