序列化二叉树
题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
- 利用数组实现序列化结果,重建过程相当于建树,用前序结果建树。
- 递归
function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
}
const arr=[]
function Serialize(pRoot)
{
// write code here
if(pRoot==null){
arr.push('#')
}else{
arr.push(pRoot.val)
Serialize(pRoot.left)
Serialize(pRoot.right)
}
}
function Deserialize()
{
// write code here
let node=null;
if(arr.length<1){
return null;
}
let number=arr.shift()
if(typeof(number)=='number'){
node=new TreeNode(number)
node.left=Deserialize();
node.right=Deserialize()
}
return node;
}