Skip to content

Commit d55e1bd

Browse files
authored
Create 297-serialize-and-deserialize-binary-tree.js
1 parent 51c85e3 commit d55e1bd

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
9+
/**
10+
* Encodes a tree to a single string.
11+
*
12+
* @param {TreeNode} root
13+
* @return {string}
14+
*/
15+
const serialize = function(root) {
16+
return rserialize(root, "");
17+
};
18+
19+
function rserialize(root, str) {
20+
if (root === null) {
21+
str += "null,";
22+
} else {
23+
str += root.val + ",";
24+
str = rserialize(root.left, str);
25+
str = rserialize(root.right, str);
26+
}
27+
28+
return str;
29+
}
30+
/**
31+
* Decodes your encoded data to tree.
32+
*
33+
* @param {string} data
34+
* @return {TreeNode}
35+
*/
36+
const deserialize = function(data) {
37+
let data_array = data.split(",").filter(el => el !== "");
38+
return rdeserialize(data_array);
39+
};
40+
41+
function rdeserialize(l) {
42+
if (l[0] === "null") {
43+
l.shift();
44+
return null;
45+
}
46+
const root = new TreeNode(+l[0]);
47+
l.shift();
48+
root.left = rdeserialize(l);
49+
root.right = rdeserialize(l);
50+
return root;
51+
}
52+
/**
53+
* Your functions will be called as such:
54+
* deserialize(serialize(root));
55+
*/

0 commit comments

Comments
 (0)