二叉树的序列化和反序列化
输入:root = [1,2,3,null,null,4,5]
输出:[1,2,3,null,null,4,5]
输入:root = []
输出:[]
public class Codec {
/**
思路分析:
BFS实现序列化和反序列化
*/
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root == null){
return "";
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
StringBuffer sb = new StringBuffer();
while(!queue.isEmpty()){
TreeNode node = queue.poll();
if(node == null){
sb.append("X,");
}else {
sb.append(node.val + ",");
queue.offer(node.left);
queue.offer(node.right);
}
}
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data == ""){
return null;
}
Queue<String> nodes = new ArrayDeque<>(Arrays.asList(data.split(",")));
TreeNode root = new TreeNode(Integer.parseInt(nodes.poll()));
Queue<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
while(!queue.isEmpty()){
TreeNode node = queue.poll();
String left = nodes.poll();
String right = nodes.poll();
if(!left.equals("X")){
node.left = new TreeNode(Integer.parseInt(left));
queue.offer(node.left);
}
if(!right.equals("X")){
node.right = new TreeNode(Integer.parseInt(right));
queue.offer(node.right);
}
}
return root;
}
}