题目
题目链接:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/
思路
使用层次遍历序列化和反序列化
代码
没有加注释,这道题挺麻烦的。
给个连接参考参考: 【10584 二叉树怎样序列化才能重建】
public class Codec {
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder("");
if(root == null) return sb.toString();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
while(size-- > 0){
root = queue.poll();
if(root != null){
sb.append(root.val+" ");
queue.offer(root.left);
queue.offer(root.right);
}else{
sb.append(root+" ");
}
}
}
return sb.toString();
}
public TreeNode deserialize(String data) {
if(data.length() == 0) return null;
String[] trees = (data.trim()).split(" ");
Queue<TreeNode> queue = new LinkedList<TreeNode>();
int index = 0;
TreeNode root = new TreeNode(Integer.valueOf(trees[index++]));
queue.offer(root);
int len = trees.length;
while (!queue.isEmpty()) {
int size = queue.size();
while (size-- > 0) {
if(index == len) {
queue.clear();
break;
}
TreeNode node = queue.poll();
if(node == null) {
continue;
}
node.left = trees[index].equals("null")?null:new TreeNode(Integer.valueOf(trees[index]));
index++;
queue.offer(node.left);
node.right = trees[index].equals("null")?null:new TreeNode(Integer.valueOf(trees[index]));
index++;
queue.offer(node.right);
}
}
return root;
}
}