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);
12
}
13
}
14

15
getNode(root);
16

17
return res.join(",");
18
};
19

20
/**
21
* Decodes your encoded data to tree.
22
*
23
* @param {string} data
24
* @return {TreeNode}
25
*/
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

39
return node;
40
}
41

42
return buildTree(arr);
43
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0