7.Binary Tree Serialization
Last updated
Last updated
/**
* 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) {
if(root==null){
return "{}";
}
StringBuilder sb=new StringBuilder();
Queue<TreeNode> queue=new LinkedList<TreeNode>();
queue.offer(root);
sb.append("{");
while(!queue.isEmpty()){
TreeNode current=queue.poll();
if(current!=null){
sb.append(String.valueOf(current.val)+",");
//注意要在这里offer left right因为如果是空就没有后续了。
//if left or right is null then push a null in it.
queue.offer(current.left);
queue.offer(current.right);
}
else{
sb.append("#,");
}
}
//delete the last comma
sb.deleteCharAt(sb.length()-1);
sb.append("}");
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.
*/
public TreeNode deserialize(String data) {
//边界一定要判断
if(data.equals("{}")){
return null;
}
//delete the {},and for substring,begin is inclusive,end is exclusive
String str=data.substring(1,data.length()-1);
//Get the array of node
String[] arr=str.split(",");
//Get the first element as root;
TreeNode root=new TreeNode(Integer.parseInt(arr[0]));
Queue<TreeNode> queue=new LinkedList<TreeNode>();
int index=1;//coz arr[0] has been in the queue
queue.offer(root);
while(!queue.isEmpty()){
TreeNode current=queue.poll();
//这里一定要判断是不是null因为offer进来好多null
if(current==null){
continue;
}
//判断元素要用equals不要用arr[i]==""
if(!arr[index].equals("#")){
TreeNode left=new TreeNode(Integer.parseInt(arr[index]));
queue.offer(left);
current.left=left;
}else{
//没有也要offer一个Null
queue.offer(null);
current.left=null;
}
index++;//每次检查完一个元素后就index++;
if(!arr[index].equals("#")){
TreeNode right=new TreeNode(Integer.parseInt(arr[index]));
queue.offer(right);
current.right=right;
}else{
queue.offer(null);
current.right=null;
}
index++;
}
return root;
}