Skip to content

Commit 469a518

Browse files
committed
Runtime 162 ms (Top 22.2%) | Memory 54.0 MB (Top 18.91%)
1 parent 9dcd7db commit 469a518

File tree

1 file changed

+30
-29
lines changed

1 file changed

+30
-29
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,20 @@
1-
/**
2-
* Encodes a tree to a single string.
3-
*
4-
* @param {TreeNode} root
5-
* @return {string}
6-
*/
7-
var serialize = function(root) {
8-
let result = [];
9-
const dfs = (r) => {
10-
if (!r) {
11-
result.push('N');
12-
return;
1+
var serialize = function (root) {
2+
if (!root) return "";
3+
let res = [];
4+
5+
function getNode(node) {
6+
if (!node) {
7+
res.push("null");
8+
} else {
9+
res.push(node.val);
10+
getNode(node.left);
11+
getNode(node.right);
1312
}
14-
result.push(r.val);
15-
dfs(r.left);
16-
dfs(r.right);
1713
}
18-
dfs(root);
19-
return result.join(",")
14+
15+
getNode(root);
16+
17+
return res.join(",");
2018
};
2119

2220
/**
@@ -25,18 +23,21 @@
2523
* @param {string} data
2624
* @return {TreeNode}
2725
*/
28-
var deserialize = function(data) {
29-
const vals = data.split(",");
30-
const dfs = (stream) => {
31-
const item = stream.shift();
32-
if (item == 'N') {
33-
return null;
34-
}
35-
const node = new TreeNode(item);
36-
node.left = dfs(stream);
37-
node.right = dfs(stream);
26+
var deserialize = function (data) {
27+
if (data === "") return null;
28+
const arr = data.split(",");
29+
30+
function buildTree(array) {
31+
const nodeVal = array.shift();
32+
33+
if (nodeVal === "null") return null;
34+
35+
const node = new TreeNode(nodeVal);
36+
node.left = buildTree(array); //build left first
37+
node.right = buildTree(array); //build right with updated array.
38+
3839
return node;
39-
};
40+
}
4041

41-
return dfs(vals);
42+
return buildTree(arr);
4243
};

0 commit comments

Comments
 (0)