449. Serialize and Deserialize BST
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 search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.
The encoded string should be as compact as possible.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
Subscribe to see which companies asked this question.
题目简介:
就是用字符串的形式存储二分图数据和二分图结构,要求能够通过自己存储的字符串再重构出二分图。
思路:
前序遍历(通过前序遍历的方式遍历二分图,将遍历结果保存为字符串)。然后再根据前序遍历的复原方式重构二分图。
整个算法耗时的关键点就是字符串拼接的过程。public String visit(TreeNode root)直接返回拼接好的子树的字符串,然后依次拼接。
之后为了避开反复拼接字符串重写了一个public void visit2(List<Integer> aList,TreeNode root)将遍历的结果存在List数组中,最后再拼接成字符串返回,但是效果没有之前的效果好。(我想第二种方式依旧躲不开字符串拼接,,,so。。。)
代码:
/**
* 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.
int index=0;
public String serialize(TreeNode root) {
//System.out.println(visit(root));
//简单的字符串拼接版本
return visit(root);
//用可扩展数组试试
/*
List<Integer> aList = new ArrayList<Integer>();
visit2(aList,root);
String aString = "";
for(Integer e:aList){
if(e != -1){
aString = aString+e+" ";
}else{
aString = aString+"N ";
}
}
return aString;
*/
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
index = 0;
String[] aTree = data.split(" ");
if(aTree.length == 1){
return null;
}else{
TreeNode aRoot = new TreeNode(Integer.parseInt(aTree[index++]));
//aRoot.val = ;
reConduct(aTree,aRoot);
return aRoot;
}
}
//按照前序遍历的方式,简单的字符串拼接版本;
private String visit(TreeNode root){
if(root != null){
return root.val+" "+visit(root.left)+visit(root.right);
}else{
return "N ";
}
}
//为了避免反复传值,用ArrayList来保存遍历的结果,效果更差。。。
private void visit2(List<Integer> aList,TreeNode root){
if(root != null){
aList.add(root.val);
visit2(aList,root.left);
visit2(aList,root.right);
}else{
aList.add(-1);
}
}
private void reConduct(String[] aTree,TreeNode root){
if(aTree[index].equals("N")){
root.left = null;
//reConduct(aTree,index+1,root,1);
index++;
}else{
TreeNode aNode = new TreeNode(Integer.parseInt(aTree[index++]));
root.left = aNode;
reConduct(aTree,aNode);
}
if(aTree[index].equals("N")){
root.right = null;
index++;
}else{
TreeNode aNode = new TreeNode(Integer.parseInt(aTree[index++]));
root.right = aNode;
reConduct(aTree,aNode);
}
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
运行结果:
(不能传图片???74.55%)