Building Red-Black Tree from sorted array in linear time

后端 未结 3 1687
清酒与你
清酒与你 2021-01-13 00:53

i know how to build it with n insertions ( each with O(log(n)) efficiency ) (n*log(n)) overall ,i also know that the equivalent structure of 2-3-4 tree can also be build wit

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-13 01:39

    A complete binary tree of height H has 2^H-1 nodes.

    To make a red black tree from a sorted list:

    1. Remove every second item from the list until you have 2^H-1 items remaining for some H. Note that you will always have enough.
    2. Build a complete tree out of the remaining items, all black.
    3. Now attach all the items you removed to the tree. Each item will be a red node, attached to whichever of the black nodes around its proper position is a leaf.

    The easiest way to do step (3) is just to do a pre-order traversal of the tree, attaching new red nodes to every black leaf until you run out of items.

    NOTE: Sasha's algorithm also works, but this one obviously works.

提交回复
热议问题