Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'.
Notice
There is no limit of how you deserialize or serialize a binary tree, LintCode will take your output of serialize
as the input of deserialize
, it won't check the result of serialize.
An example of testdata: Binary tree {3,9,20,#,#,15,7}
, denote the following structure:
3
/ \
9 20
/ \
15 7
Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.
You can use other method to do serializaiton and deserialization.
一种速度不快,但是非常好理解的方法
java
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* This method will be invoked first, you should design your own algorithm
* to serialize a binary tree which denote by a root node to a string which
* can be easily deserialized by your own "deserialize" method later.
*/
public String serialize(TreeNode root) {
// write your code here
StringBuffer sb = new StringBuffer();
if (root == null) {
sb.append("#,");
return sb.toString();
}
sb.append(root.val + ",");
sb.append(serialize(root.left));
sb.append(serialize(root.right));
return sb.toString();
}
/**
* This method will be invoked second, the argument data is what exactly
* you serialized at method "serialize", that means the data is not given by
* system, it's given by your own serialize method. So the format of data is
* designed by yourself, and deserialize it here as you serialize it in
* "serialize" method.
*/
int p = -1;
public TreeNode deserialize(String data) {
// write your code here
p++;
String[] strs = data.split(",");
TreeNode root = null;
while (!strs[p].equals("#")) {
root = new TreeNode(Integer.valueOf(strs[p]));
root.left = deserialize(data);
root.right = deserialize(data);
}
return root;
}
}