二叉树序列化反序列化
实现
function serialize(tree){
var arr=[];
innerSerialize(tree,arr);
return arr.join(",");
function innerSerialize(tree,arr){
if(!tree)
//占位符,可用其他代替
arr.push("#");
}else{
arr.push(tree.value);
innerSerialize(tree.left,arr);
innerSerialize(tree.right,arr);
}
}
}
function deserialize(serializedTree){
var arr=seralizedTree.split(",");
return innerDeserialize();
function innerDeserialize(){
if(!arr.length){
return;
}
var val=arr.shift();
if(val==="#"){
return;
}
var node={
value:val
};
node.left=innerDeserialize();
node.right=innerDeserialize();
return node;
}
}
var testTree={
value:1,
left:{
value:2
},
right:{
value:3,
left:{
value:4
},
right:{
value:5
}
}
}
var serializedTree=serialize(testTree);
console.log(serializedTree);
var deserializedTree=deserialize(serializedTree);
console.log(deserializedTree);