题目:请实现两个函数,分别用来序列化和反序列化二叉树
思路:层顺遍历二叉树 并保存所有的空节点
/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ // 层序遍历最后结果 [1,2,3,null,null,4,5,null,null,null,null]
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) return "[]";
StringBuilder sb = new StringBuilder("[");
LinkedList<TreeNode> q = new LinkedList<>();
q.add(root);
while(q.size() > 0 ) {
TreeNode t = q.removeFirst();
if (t == null) {
sb.append("null").append(",");
}else {
sb.append(t.val).append(",");
q.add(t.left);
q.add(t.right);
}
}
// 移除最后一个多余的 ,
sb.deleteCharAt(res.length() - 1);
return sb.append("]").toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data.equals("[]")) return null;
String[] vals = data.substring(1, data.length() - 1).split(",");
TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
Queue<TreeNode> queue = new LinkedList() {{ add(root); }};
int i = 1;
while(!queue.isEmpty()) {
TreeNode node = queue.poll();
if(!vals[i].equals("null")) {
node.left = new TreeNode(Integer.parseInt(vals[i]));
queue.add(node.left);
}
i++;
if(!vals[i].equals("null")) {
node.right = new TreeNode(Integer.parseInt(vals[i]));
queue.add(node.right);
}
i++;
}
return root;
}