Data Structures · Visualization
Interval Tree: Insert
Interval Tree
Insertion walks down by low endpoint exactly like a BST insert, then repairs maxHigh on the way back up. Time: O(log n) average, O(n) worst case unbalanced. Space: O(1) extra per insert.
Big-O: Insert O(log n); overlap query O(log n + k).
Interval Tree: Insert
Interval TreeInsertion walks down by low endpoint exactly like a BST insert, then repairs maxHigh on the way back up. Each ancestor's maxHigh becomes the maximum of its own high and both children's maxHigh — one bottom-up pass keeps every future search correctly pruned.
How Insert Works
- Compare the new low with the node: go left if smaller, right otherwise.
- Insert at the first empty spot, like a plain BST.
- Walk back to the root recomputing maxHigh at each ancestor.
- maxHigh[node] = max(node.high, maxHigh[left], maxHigh[right]).
Insert Worked Example
Input: Insert [9, 12] into a tree holding [1, 3], [5, 8], [2, 6]
- 9 > root low 2 → go right to [5, 8].
- 9 > 5 → empty right slot: place [9, 12].
- Recompute: maxHigh of [5, 8] becomes 12.
- Recompute: root maxHigh becomes 12.
Output: Tree holds 4 intervals; root maxHigh = 12
Press ▶ Run to watch it step by step.
def insert(root, iv):
if not root:
return {'iv': iv, 'max': iv[1]}
if iv[0] < root['iv'][0]:
root['left'] = insert(root.get('left'), iv)
else:
root['right'] = insert(root.get('right'), iv)
root['max'] = max(root['iv'][1], ...) # repair up
return root
# example: insertBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Insert Time & Space Complexity
When to Use Insert
- Live schedulers inserting bookings as users click
- Windowing systems tracking visible rectangles
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.