forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathData Stream as Disjoint Intervals.js
55 lines (52 loc) · 1.3 KB
/
Data Stream as Disjoint Intervals.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
var SummaryRanges = function() {
this.tree = null // { val, left?, right? }
};
/**
* @param {number} val
* @return {void}
*/
SummaryRanges.prototype.addNum = function(val) {
if (!this.tree) {
this.tree = { val }
} else {
let node = this.tree
let parent, side
while (node) {
if (node.val === val) { return }
parent = node
side = node.val > val ? 'left' : 'right'
node = node[side]
}
parent[side] = { val }
}
};
/**
* @return {number[][]}
*/
SummaryRanges.prototype.getIntervals = function() {
// travel from left to right
// generate intervals
// > (x === last[1] + 1) ? update last[1] : create a new one
const travel = (node, check) => {
if (!node) { return }
travel(node.left, check)
check(node.val)
travel(node.right, check)
}
const result = []
const check = val => {
if (!result.length || val > result[result.length - 1][1] + 1) {
result.push([val, val])
} else {
result[result.length - 1][1] = val
}
}
travel(this.tree, check)
return result
};
/**
* Your SummaryRanges object will be instantiated and called as such:
* var obj = new SummaryRanges()
* obj.addNum(val)
* var param_2 = obj.getIntervals()
*/