采用先序遍历序列化,然后先序遍历解序列化。序列化的时候每个结点值后面都要加一个"!"用来分隔。如果遇到空结点那就加"#"表示。
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 "";
StringBuffer str=new StringBuffer();
serialize1(root,str);
return str.toString();
}
void serialize1(TreeNode root,StringBuffer str)
{
if(root==null)
{str.append("#!");return;}
str.append(root.val);
str.append("!");
serialize1(root.left,str);
serialize1(root.right,str);
}
TreeNode Deserialize(String str) {
if(str.equals("")||str.charAt(0)=='#'){
return null;
}
String[] str1=str.split("!");
return deserialize(str1);
}
int index=-1;
TreeNode deserialize(String[] str1){
index++;
if(!str1[index].equals("#")){
TreeNode root=new TreeNode(Integer.parseInt(str1[index]));
root.left=deserialize(str1);
root.right=deserialize(str1);
return root;
}
return null;
}
}