Interval tree algorithm that supports merging of intervals with no overlap

拈花ヽ惹草 提交于 2019-12-02 21:59:12

The problem I see is that inserting a large interval can wipe out a large chunk of the tree, making it difficult to recover the red-black invariants.

I think it would be easier to use a splay tree, as follows. For simplicity, each tree contains two sentinels, an interval A to the left of all other intervals and an interval Z to the right. When inserting an interval I, splay I's predecessor-to-be H to the root of the tree. The tree looks like

   H
  / \
...  X
    / \
  ... ...

Now detach X and splay I's successor-to-be J to the root.

   H       J
  /       / \
...     ... ...

At this point all of the intervals that overlap I are in J's left subtree. Detach that subtree and put all of its nodes on the free list, extending I if necessary. Make I the parent of H and J

     I
    / \
   H   J
  /     \
...     ...

and continue on our merry way. This operation is O(log n) amortized, where n is the number of tree nodes (this can be proved by examining the splay tree potential function and doing a lot of algebra).


I should add that there's a natural recursive tree-to-tree merge by inserting the root of one tree and then merging the left and right subtrees. I don't know how to analyze it off-hand.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!