Question 12.2.5: Write addition and deletion procedures that keep the tree ba......

Write addition and deletion procedures that keep the tree balanced.
The running time should not exceed C. (tree height). It is allowed to store additional information (needed for balancing) at the vertices of the tree.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

For each vertex we keep the difference between the heights of its right and left subtrees:

diff [i] = (the height of the right subtree of i) -(the height of the left subtree of i).

We need four procedures that correspond to left/right, small/big rotations. Let us first make two remarks. (1) We want to keep the number of the tree root unchanged during the rotation. (Otherwise it would be necessary to update the pointer at the father vertex, which is inconvenient.) This can be done, because the numbers of tree vertices may be chosen independently of their content. (In our pictures, the number is drawn near the vertex while the content is drawn inside it.)

(2) After the transformation, we should update values in the diff array. To do this, it is enough to know the heights of trees P, Q, . . . up to a constant (only differences are important), so we may assume that one of the heights is equal to 0.
Here are the rotation procedures

procedure SR (a:integer);  {small right rotation at a}
I var b: l..n; val_a,val b: T; h_P,h_Q,h_R:  integer;
begin

b := right  [a]; {b <> null}
val_a := val [a]; val b := val [b];
h_Q := O; h_R := diff[b];  h_P := (max(h_Q,h_R) +1) -diff [a] ;
val [a] := val_b; val [b] := val_a;
right  [a] := right  [b] {subtree R}
right  [b] := left  [b] {subtree Q}
left [b] := left [a] {subtree P}
left  [a] := b;
diff  [b] := h_Q – h P;
diff  [a] := h R-  (max (h_P, h_Q) + 1);

end ;

procedure BR(a : integer) ;{big right rotation at a}
var b, c: 1 . . n; val_a,val_b,val_c: T;
h_P,h_Q,h_R,h_S: integer;
begin

b := right [a]; c := left [b]; {,c <> null}
val_a := val [a]; val_b := val [b]; val_c := val [c];
h_Q := 0; h_R := diff[c]; h_S := (max(h_Q,h_R)+l)+diff[b];
h_P := 1 + max (h_S, h_S-diff[b]) – diff [a];
val [a] := val_c; val [c] := val_a;
left [b] := right [c] {subtree R}
right [c] := left [c] {subtree Q}
left [c] := left [a] {subtree P}
left [a] := c;
diff [b] := h_S – h_R;
diff [c] := h_Q – h_P;
diff [a] := max (h_S, h_R) -max (h_P, h_Q);

end;

The (small and big) left rotations are similar.

Related Answered Questions

Question: 12.2.2

Verified Answer:

By induction over n, we prove that Φ_{n+2} ...
Question: 12.2.1

Verified Answer:

The maximal number of vertices is equal to ...
Question: 12.1.3

Verified Answer:

val [null]  := t; x := root ; while t <> val...
Question: 12.1.2

Verified Answer:

if root = null then begin ..t is not in the tree e...