-
Notifications
You must be signed in to change notification settings - Fork 1
/
tree-serialize.js
47 lines (38 loc) · 978 Bytes
/
tree-serialize.js
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
let { root, Node } = require('./tree-demo-standard');
// 先序
function serialize(node) {
if (!node) {
return '#!';
}
let res = node.value + '!';
res += serialize(node.left);
res += serialize(node.right);
return res;
}
function unserialize(arr) {
let c = arr.shift();
if (c === '#') {
return null;
}
let node = new Node(c);
node.left = unserialize(arr);
node.right = unserialize(arr);
return node;
}
console.log(serialize(root));
let str = '8!1!5!3!#!#!4!#!#!2!#!9!#!#!7!6!#!#!#';
let rootBack = unserialize(str.split('!'));
console.log('before', root.toString());
console.log('after ', rootBack.toString());
//-------------------
// 另一种格式序列化
var arr = [];
function theOtherSerialize(node) {
arr.push(node.value);
if (node.left) theOtherSerialize(node.left);
else arr.push('#');
if (node.right) theOtherSerialize(node.right);
else arr.push('#');
}
theOtherSerialize(root);
console.log('the theOtherSerialize:\n', arr.join('!'));