Question 12.1.4: Write a procedure that adds an element t to a set represe......

Write a procedure that adds an element t to a set represented as an (ordered) T-tree. (If t is already present, nothing should be done.)

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

The procedure get_free (var i : integer) produces a free integer i in 1 . . n (that is, an integer that is not a number of any vertex) and updates the free list. (For simplicity, we assume that free integers exist.)

procedure get_free  (var i: integer) ;
begin

{free <> null}
i := free;
free := left  [free];

end ;
Using this procedure, we write:
if root = null then begin

get_free  (root) ;
left [root]  := null; right  [root]  := null;
val [root]  := t;

end else begin

x := root ;
{invariant:  it remains to add t to a (nonempty)  subtree
rooted at x}
while  ((t < val [x]) and (left  [x] <> null)) or
((t > val [x]) and (right  [x] <> null)) do begin

if t < val [x] then begin

x := left  Ix];

end else begin {t > val [x]}

x := right  [x];

end;

end ;

if t <> val [x] then begin {t is not in the tree)

get_free (i);
left [i] := null; right [i] := null;
val [i] := t;
if t < val [x] then begin

I left [x] := i;

end else begin {t > val [x]}

right [x] := i;

end;

end;

end;

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...