请实现两个函数,分别用来序列化和反序列化二叉树。
import java.util.*;
import java.lang.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
String Serialize(TreeNode root) {
if(root == null) return "[]";
// 序列化[1,2,3,null,4,5]
StringBuilder res = new StringBuilder("[");
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty()) {
TreeNode node = q.poll();
if(node != null) {
res.append(node.val+",");
q.add(node.left);
q.add(node.right);
}else {
res.append("null,");
}
}
res.append("]");
return res.toString();
}
TreeNode Deserialize(String str) {
if(str.equals("[]")) return null;
String[] sarr = str.substring(1,str.length()-1).split(",");
Queue<TreeNode> q = new LinkedList<>();
TreeNode root = new TreeNode(Integer.parseInt(sarr[0]));
q.add(root);
int i = 1;
while(!q.isEmpty()) {
TreeNode node = q.poll();
if(!sarr[i].equals("null")) {
node.left = new TreeNode(Integer.parseInt(sarr[i]));
q.add(node.left);
}
i++;
if(!sarr[i].equals("null")) {
node.right = new TreeNode(Integer.parseInt(sarr[i]));
q.add(node.right);
}
i++;
}
return root;
}
}