-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterval_tree.py
More file actions
72 lines (61 loc) · 2.55 KB
/
Copy pathinterval_tree.py
File metadata and controls
72 lines (61 loc) · 2.55 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from typing import Any, List, Optional
class IntervalNode:
def __init__(self, low: Any, high: Any, data: Any = None):
self.low = low
self.high = high
self.max = high # Maximum high in this subtree
self.data = data
self.left: Optional[IntervalNode] = None
self.right: Optional[IntervalNode] = None
class IntervalTree:
def __init__(self):
self.root: Optional[IntervalNode] = None
def insert(self, low: Any, high: Any, data: Any = None) -> None:
"""
Inserts a new interval [low, high) into the tree.
"""
new_node = IntervalNode(low, high, data)
if not self.root:
self.root = new_node
return
self._insert_node(self.root, new_node)
def _insert_node(self, root: IntervalNode, node: IntervalNode) -> None:
# Standard BST insertion based on low endpoint
if node.low < root.low:
if not root.left:
root.left = node
else:
self._insert_node(root.left, node)
else:
if not root.right:
root.right = node
else:
self._insert_node(root.right, node)
# Update the max value of the ancestor node
if root.max < node.high:
root.max = node.high
def overlap_search(self, low: Any, high: Any) -> List[Any]:
"""
Finds all intervals in the tree that overlap with the query interval [low, high).
An interval [a, b) overlaps with [x, y) if max(a, x) < min(b, y).
"""
results = []
self._overlap_search_node(self.root, low, high, results)
return results
def _overlap_search_node(self, root: Optional[IntervalNode], low: Any, high: Any, results: List[Any]) -> None:
if not root:
return
# Check for overlap: max(root.low, low) < min(root.high, high)
if root.low < high and low < root.high:
results.append({
"low": root.low,
"high": root.high,
"data": root.data
})
# If left child is not empty and its max endpoint is greater than query's low endpoint,
# then there might be an overlap in the left subtree
if root.left and root.left.max > low:
self._overlap_search_node(root.left, low, high, results)
# We must search the right subtree if root's low endpoint is less than query's high endpoint
if root.right and root.low < high:
self._overlap_search_node(root.right, low, high, results)