问题:
用自己的方法把二叉树转化为字符串,在用自己的方法把这个字符串转为二叉树
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
思路:先序遍历输出二叉树,遇到空就输出null
再递归一下来吧字符串转化为树
程序:
class pointer {
int pos = 0;
}
public class Codec {
public String post(TreeNode root) {
if(root == null) return "null,";
else return Integer.toString(root.val)+","+post(root.left)+post(root.right);
}
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
return post(root);
}
public TreeNode decode(String[] str, pointer p) {
if(str[p.pos].equals("null")) {
p.pos++;
return null;
}
else {
TreeNode rt = new TreeNode(Integer.parseInt(str[p.pos]));
p.pos++;
rt.left = decode(str, p);
rt.right = decode(str, p);
return rt;
}
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] strs = data.split(",");
return decode(strs, new pointer());
}
}