代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) {
return "#!";
}
String res = root.val + "!";
res += serialize(root.left);
res += serialize(root.right);
return res;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String preStr) {
String[] values = preStr.split("!");
Queue<String> queue = new LinkedList<>();
for(int i = 0; i != values.length; i++){
queue.offer(values[i]);
}
return deserialize(queue);
}
private TreeNode deserialize(Queue<String> queue){
String value = queue.poll();
if(value.equals("#")){
return null;
}
TreeNode node = new TreeNode(Integer.valueOf(value));
node.left = deserialize(queue);
node.right = deserialize(queue);
return node;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));