-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0449-serialize-and-deserialize-bst.js
More file actions
53 lines (42 loc) · 1.25 KB
/
0449-serialize-and-deserialize-bst.js
File metadata and controls
53 lines (42 loc) · 1.25 KB
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
/**
* Serialize And Deserialize Bst
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var serialize = function (root) {
if (!root) {
return '';
}
const outputCollection = [];
function treeTraversal(nodeElement) {
if (!nodeElement) {
return;
}
outputCollection.push(nodeElement.val);
treeTraversal(nodeElement.left);
treeTraversal(nodeElement.right);
}
treeTraversal(root);
return outputCollection.join(',');
};
var deserialize = function (data) {
if (!data) {
return null;
}
const numericalSegments = data.split(',').map(Number);
function treeBuilder(currentValues, minimumBound, maximumBound) {
if (currentValues.length === 0) {
return null;
}
let candidateValue = currentValues[0];
if (candidateValue < minimumBound || candidateValue > maximumBound) {
return null;
}
let extractedValue = currentValues.shift();
let treeNodeInstance = new TreeNode(extractedValue);
treeNodeInstance.left = treeBuilder(currentValues, minimumBound, extractedValue);
treeNodeInstance.right = treeBuilder(currentValues, extractedValue, maximumBound);
return treeNodeInstance;
}
return treeBuilder(numericalSegments, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
};