题目描述:请实现两个函数,分别用来序列化和反序列化二叉树
思路:采用层次遍历方法层次序列化和反序列化二叉树。节点为空则用#表示,每个节点间用!隔开。反序列化相当于重做层遍历。
代码:
import java.util.*;
/*
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 "#!";
}
String res = root.val + "!";
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
root = queue.poll();
if(root.left != null){
queue.offer(root.left);
res += root.left.val + "!";
}else{
res += "#!";
}
if(root.right != null){
queue.offer(root.right);
res += root.right.val + "!";
}else{
res += "#!";
}
}
return res;
}
TreeNode Deserialize(String str) {
String[] values = str.split("!");
int index = 0;
TreeNode root = gn(values[index++]);
Queue<TreeNode> queue = new LinkedList<>();
if(root != null){
queue.offer(root);
}
TreeNode node = null;
while(!queue.isEmpty()){
node = queue.poll();
node.left = gn(values[index++]);
node.right = gn(values[index++]);
if(node.left != null){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
}
return root;
}
public TreeNode gn(String str){
if(str.equals("#")){
return null;
}
return new TreeNode(Integer.valueOf(str));
}
}