递归
可以使用前序遍历将二叉树序列化为字符串,遇到null用字符串“null,”代替。
反序列化时将序列化的结果转化为String数组,每次读取一个字符串,如果是数字则按照前序遍历继续递归。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
private StringBuffer buffer = new StringBuffer();
private int number;
private int index = 0;
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root == null){
buffer.append("null,");
return buffer.toString();
}
buffer.append(root.val+",");
serialize(root.left);
serialize(root.right);
return buffer.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] nodes = data.split(",");
//System.out.print(data);
return rdeserialize(nodes);
}
private TreeNode rdeserialize(String[] data){
if(!readOne(data)){
return null;
}
TreeNode root = new TreeNode(number);
root.left = rdeserialize(data);
root.right = rdeserialize(data);
return root;
}
//每次读取一个字符
private boolean readOne(String[] data){
if(data[index].equals("null")){
++index;
return false;
}else{
number = Integer.valueOf(data[index]);
++index;
return true;
}
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));