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.
For example, you may serialize the following tree
1 / \ 2 3 / \ 4 5as
"[1,2,3,null,null,4,5]"
, just the same as
how LeetCode OJ serializes a binary tree
. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
实现的时候还是参考了提示。发现序列化的时候是正确的,但是反序列化的时候对于存放的结构还不是很清楚,结果找了很长时间。先序遍历,左边的节点会存放在右边的节点前面,所以可以通过递归调用找出父节点的左孩子,然后找出右孩子。每一次取元素是从list的头取出一个元素,正好跟序列化时的顺序相对应。序列化的时候采用先序遍历,先存入父节点,然后把它的左孩子存入,然后再存入他的右孩子。
代码:
public String serialize(TreeNode root) {
if(root == null){
return "";
}
return sBuilder(root, new StringBuffer());
}
//pre order
private String sBuilder(TreeNode root, StringBuffer sb){
if(root == null) return "#,";
sb.append(root.val+",");
sb.append(sBuilder(root.left, new StringBuffer()));
sb.append(sBuilder(root.right, new StringBuffer()));
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data == null || data.length() == 0) return null;
String[] split = data.split(",");
LinkedList<String> nodes = new LinkedList<>(Arrays.asList(split));
return dBuilder(nodes);
}
private TreeNode dBuilder(LinkedList<String> nodes){
String val = nodes.remove();
if(val.equals("#")){
return null;
}else{
TreeNode node = new TreeNode(Integer.parseInt(val));
node.left = dBuilder(nodes);
node.right = dBuilder(nodes);
return node;
}
}