13-2 Join operation on red-black trees

The join operation takes two dynamic sets S1S_1 and S2S_2 and an element xx such that for any x1S1x_1 \in S_1 and x2S2x_2 \in S_2, we have x1.keyx.keyx2.keyx_1.key \le x.key \le x_2.key. It returns a set S=S1{x}S2S = S_1 \cup \{x\} \cup S_2. In this problem, we investigate how to implement the join operation on red-black trees.

a. Given a red-black tree TT, let us store its black-height as the new attribute T.bhT.bh. Argue that RB-INSERT\text{RB-INSERT} and RB-DELETE\text{RB-DELETE} can maintain the bhbh attribute without requiring extra storage in the nodes of the tree and without increasing the asymptotic running times. Show that while descending through TT, we can determine the black-height of each node we visit in O(1)O(1) time per node visited.

We wish to implement the operation RB-JOIN(T1,x,T2)\text{RB-JOIN}(T_1, x, T_2), which destroys T1T_1 and T2T_2 and returns a red-black tree T=T1{x}T2T = T_1 \cup \{x\} \cup T_2. Let nn be the total number of nodes in T1T_1 and T2T_2.

b. Assume that T1.bhT2.bhT_1.bh \ge T_2.bh. Describe an O(lgn)O(\lg n)-time algorithm that finds a black node yy in T1T_1 with the largest key from among those nodes whose black-height is T2.bhT_2.bh.

c. Let TyT_y be the subtree rooted at yy. Describe how Ty{x}T2T_y \cup \{x\} \cup T_2 can replace TyT_y in O(1)O(1) time without destroying the binary-search-tree property.

d. What color should we make xx so that red-black properties 1, 3, and 5 are maintained? Describe how to enforce properties 2 and 4 in O(lgn)O(\lg n) time.

e. Argue that no generality is lost by making the assumption in part (b). Describe the symmetric situation that arises when T1.bhT2.bhT_1.bh \le T_2.bh.

f. Argue that the running time of RB-JOIN\text{RB-JOIN} is O(lgn)O(\lg n).

a.

  • Initialize: bh=0bh = 0.
  • RB-INSERT\text{RB-INSERT}: if in the last step the root is red, we increase bhbh by 11.
  • RB-DELETE\text{RB-DELETE}: if xx is root, we decrease bhbh by 11.
  • Each node: in the simple path, decrease bhbh by 11 each time we find a black node.

b. Move to the right child if the node has a right child, otherwise move to the left child. If the node is black, we decease bhbh by 11. Repeat the step until bh=T2.bhbh = T_2.bh.

c. The time complexity is O(1)O(1).

RB-JOIN'(T[y], x, T[2])
    TRANSPLANT(T[y], x)
    x.left = T[y]
    x.right = T[2]
    T[y].parent = x
    T[2].parent = x

d. Red. Call INSERT-FIXUP(T[1], x)\text{INSERT-FIXUP(T[1], x)}.

The time complexity is O(lgn)O(\lg n).

e. Same, if T1.bhT2.bhT_1.bh\le T_2.bh, then we can use the above algorithm symmetrically.

f. O(1)+O(lgn)=O(lgn)O(1) + O(\lg n) = O(\lg n).