7.Binary Tree Serialization
1.Description(Medium)
Notice
3
/ \
9 20
/ \
15 72.Code
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)+",");
//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();
if(current==null){
continue;
}
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;
}Previous177.Convert Sorted Array to Binary Search Tree With Minimal HeightNext72,73.Construct Binary Tree
Last updated