题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
代码
思路:
- 序列化,将节点值存入数组中,空节点则使用特殊标记存入数组中。
- 反序列化,从数组中获取元素,为number类型则生成节点,为特殊标记,则为空节点
var arr=[];
function Serialize(pRoot)
{
// write code here
if(pRoot==null){
arr.push('#')
return;
}
arr.push(pRoot.val);
Serialize(pRoot.left)
Serialize(pRoot.right)
}
function Deserialize(s)
{
// write code here
if(arr==null){
return null;
}
if(arr.length<1){
return null;
}
var root=null;
var temp=arr.shift();
if(typeof temp=='number'){
root=new TreeNode(temp);
root.left=Deserialize(arr);
root.right=Deserialize(arr);
}
return root;
}