-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0297-serialize-and-deserialize-binary-tree.js
85 lines (68 loc) · 1.94 KB
/
0297-serialize-and-deserialize-binary-tree.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* Encodes a tree to a single string.
* https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solution/
* Time O(N) | Space O(H)
* @param {TreeNode} root
* @return {string}
*/
var serialize = function(root, result = []) {
serial(root, result);
return result;
};
const serial = (root, result) => {
const isBase = root === null;
if (isBase) return result.push(null);
dfsSerialize(root, result);
}
const dfsSerialize = (node, result) => {
result.push(node.val);
serial(node.left, result);
serial(node.right, result);
};
/**
* Encodes a tree to a single string.
* https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solution/
* Time O(N) | Space O(H)
* @param {TreeNode} root
* @return {string}
*/
var serialize = function(root) {
const isBaseCase = root === null;
if (isBaseCase) return [ null ];
return dfsSerializeIterative([ root ]);
};
const dfsSerializeIterative = (stack, result = []) => {
while (stack.length) {
const curr = stack.pop();
const isNull = curr === null;
if (isNull) {
result.push(null);
continue;
}
result.push(curr.val);
stack.push(curr.right);
stack.push(curr.left);
}
return result;
}
/**
* Decodes your encoded data to tree.
* https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solution/
* Time O(N) | Space O(H)
* @param {string} data
* @return {TreeNode}
*/
var deserialize = function(data) {
const isBaseCase = !data.length;
if (isBaseCase) return null;
const val = data.shift();
const isNull = val === null;
if (isNull) return null;
return dfsDeserialize(val, data)
};
const dfsDeserialize = (val, data) => {
const node = new TreeNode(val);
node.left = deserialize(data);
node.right = deserialize(data);
return node;
}