序列化二叉树

序列化二叉树

题目描述

请实现两个函数,分别用来序列化和反序列化二叉树

  • 利用数组实现序列化结果,重建过程相当于建树,用前序结果建树。
  • 递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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;
}