Skip to content

Commit d31e652

Browse files
committed
Create 297. 二叉树的序列化与反序列化.js
1 parent 0c7fde1 commit d31e652

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
function TreeNode(val) {
2+
this.val = val;
3+
this.left = this.right = null;
4+
}
5+
6+
/**
7+
* Definition for a binary tree node.
8+
* function TreeNode(val) {
9+
* this.val = val;
10+
* this.left = this.right = null;
11+
* }
12+
*/
13+
14+
/**
15+
* Encodes a tree to a single string.
16+
*
17+
* @param {TreeNode} root
18+
* @return {string}
19+
*/
20+
var serialize = function (root) {
21+
if (!root) {
22+
return '';
23+
}
24+
const list = [root];
25+
const result = [];
26+
while (list.length > 0 && list.some((l) => l)) {
27+
const node = list.shift();
28+
result.push(node && node.val);
29+
if (node) {
30+
list.push(node.left);
31+
list.push(node.right);
32+
}
33+
}
34+
return result.map((x) => (typeof x === 'number' ? x : 'null')).join(',');
35+
};
36+
37+
/**
38+
* Decodes your encoded data to tree.
39+
*
40+
* @param {string} data
41+
* @return {TreeNode}
42+
*/
43+
var deserialize = function (data) {
44+
if (data.length === 0) {
45+
return null;
46+
}
47+
const arr = data.split(',');
48+
const root = new TreeNode(parseInt(arr[0]));
49+
const list = [root];
50+
let i = 1;
51+
while (list.length > 0 && i < arr.length) {
52+
const node = list.shift();
53+
let nextVal = NaN;
54+
55+
nextVal = arr[i] === 'null' ? NaN : parseInt(arr[i]);
56+
if (!isNaN(nextVal)) {
57+
node.left = new TreeNode(nextVal);
58+
list.push(node.left);
59+
}
60+
i++;
61+
nextVal = arr[i] === 'null' ? NaN : parseInt(arr[i]);
62+
if (!isNaN(nextVal)) {
63+
node.right = new TreeNode(nextVal);
64+
list.push(node.right);
65+
}
66+
i++;
67+
}
68+
return root;
69+
};
70+
71+
/**
72+
* Your functions will be called as such:
73+
* deserialize(serialize(root));
74+
*/

0 commit comments

Comments
 (0)