树的序列化和反序列化之二
一颗普通树进行序列化和反序列化的算法
测试用例:
Client ct = new Client();
String para = "1;2,3,4;null:5,6:null;null:7,8;null:null;";
Tree tree = ct.unSerializeTree(para);
System.out.println(ct.serializeTree(tree));
class Tree {
public int val;
public ArrayList<Tree> childs;
public Tree(int x){
this.val = x;
}
}
//把树序列化为字符串
public String serializeTree(Tree tree){
//定义与初始化
String result = "";
LinkedList<ArrayList<Tree>> queueLayer = new LinkedList<ArrayList<Tree>>();//层队列
ArrayList<Tree> treeList = new ArrayList<Tree>();
treeList.add(tree);
queueLayer.offer(treeList);
while(!queueLayer.isEmpty()){//每次循环处理一层
//先把层队列的数据导入到处理队列,并清空层队列
ArrayList<ArrayList<Tree>> queueHandle = new ArrayList<ArrayList<Tree>>();//处理队列
for(ArrayList<Tree> oneQueueLayer:queueLayer){
queueHandle.add(oneQueueLayer);
}
queueLayer.clear();
//开始处理这一层
for(ArrayList<Tree> oneQueueHandle:queueHandle){//每次处理一组
//为空判断
if(oneQueueHandle == null){
result += "null,";
}else{
for(Tree node:oneQueueHandle){
result += node.val + ",";
queueLayer.offer(node.childs);
}
}
result = result.substring(0, result.length()-1);
result += ":";
}
result = result.substring(0, result.length()-1);
result += ";";
}
return result;
}
//把字符串反序列化为树
public Tree unSerializeTree(String str){
LinkedList<Tree> list = new LinkedList<Tree>();
//首先分层
String[] layer = str.split(";");
int len = layer.length;
if(len == 0){
return null;
}
//初始化
int rootVal = Integer.valueOf(layer[0]);
Tree result = new Tree(rootVal);
list.offer(result);
//对每一层,进行处理
int i = 1;
while(!list.isEmpty() && i < len){
String[] groupsStr = layer[i].split(":");
for(String oneGroupStr : groupsStr){
if(oneGroupStr.equals("null")){
list.poll();
}else{
ArrayList<Tree> chd = new ArrayList<Tree>();
String[] eles = oneGroupStr.split(",");
for(String ele : eles){
int eleVal = Integer.valueOf(ele);
Tree inListTree = new Tree(eleVal);
chd.add(inListTree);
list.offer(inListTree);
}
Tree outListTree = list.poll();
outListTree.childs = chd;
}
}
i++;
}
//返回
return result;
}