Data Stream as Disjoint Intervals LeetCode solution in JavaScript

1
var SummaryRanges = function () {
2
this.tree = null; // { val, left?, right? }
3
};
4

5
/**
6
* @param {number} val
7
* @return {void}
8
*/
9
SummaryRanges.prototype.addNum = function (val) {
10
if (!this.tree) {
11
this.tree = { val };
12
} else {
13
let node = this.tree;
14
let parent, side;
15
while (node) {
16
if (node.val === val) {
17
return;
18
}
19
parent = node;
20
side = node.val > val ? "left" : "right";
21
node = node[side];
22
}
23
parent[side] = { val };
24
}
25
};
26

27
/**
28
* @return {number[][]}
29
*/
30
SummaryRanges.prototype.getIntervals = function () {
31
// travel from left to right
32
// generate intervals
33
// > (x === last[1] + 1) ? update last[1] : create a new one
34
const travel = (node, check) => {
35
if (!node) {
36
return;
37
}
38
travel(node.left, check);
39
check(node.val);
40
travel(node.right, check);
41
};
42
const result = [];
43
const check = (val) => {
44
if (!result.length || val > result[result.length - 1][1] + 1) {
45
result.push([val, val]);
46
} else {
47
result[result.length - 1][1] = val;
48
}
49
};
50
travel(this.tree, check);
51
return result;
52
};
53

54
/**
55
* Your SummaryRanges object will be instantiated and called as such:
56
* var obj = new SummaryRanges()
57
* obj.addNum(val)
58
* var param_2 = obj.getIntervals()
59
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0