25.11.2014 Views

Algorithms and Data Structures

Algorithms and Data Structures

Algorithms and Data Structures

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

N.Wirth. <strong>Algorithms</strong> <strong>and</strong> <strong>Data</strong> <strong>Structures</strong>. Oberon version 192<br />

1. h = 0: the subtree p requires no changes of the tree structure.<br />

2. h = 1: node p has obtained a sibling.<br />

3. h = 2: the subtree p has increased in height.<br />

PROCEDURE search (VAR p: Node; x: INTEGER; VAR h: INTEGER);<br />

VAR q, r: Node; (* ADenS472_BBtrees *)<br />

BEGIN<br />

(*h=0*)<br />

IF p = NIL THEN (*insert new node*)<br />

NEW(p); p.key := x; p.L := NIL; p.R := NIL; p.lh := FALSE; p.rh := FALSE;<br />

h := 2<br />

ELSIF x < p.key THEN<br />

search(p.L, x, h);<br />

IF h > 0 THEN (*left branch has grown or received sibling*)<br />

q := p.L;<br />

IF p.lh THEN<br />

h := 2; p.lh := FALSE;<br />

IF q.lh THEN (*LL*)<br />

p.L := q.R; q.lh := FALSE; q.R := p; p := q<br />

ELSE (*q.rh, LR*)<br />

r := q.R; q.R := r.L; q.rh := FALSE; r.L := p.L; p.L := r.R; r.R := p; p := r<br />

END<br />

ELSE<br />

DEC(h);<br />

IF h = 1 THEN p.lh := TRUE END<br />

END<br />

END<br />

ELSIF x > p.key THEN<br />

search(p.R, x, h);<br />

IF h > 0 THEN (*right branch has grown or received sibling*)<br />

q := p.R;<br />

IF p.rh THEN<br />

h := 2; p.rh := FALSE;<br />

IF q.rh THEN (*RR*)<br />

p.R := q.L; q.rh := FALSE; q.L := p; p := q<br />

ELSE (*q.lh, RL*)<br />

r := q.L; q.L := r.R; q.lh := FALSE; r.R := p.R; p.R := r.L; r.L := p; p := r<br />

END<br />

ELSE<br />

DEC(h);<br />

IF h = 1 THEN p.rh := TRUE END<br />

END<br />

END<br />

END<br />

END search;<br />

Note that the actions to be taken for node rearrangement very strongly resemble those developed in the<br />

AVL-balanced tree search algorithm. It is evident that all four cases can be implemented by simple pointer<br />

rotations: single rotations in the LL <strong>and</strong> RR cases, double rotations in the LR <strong>and</strong> RL cases. In fact,<br />

procedure search appears here slightly simpler than in the AVL case. Clearly, the SBB-tree scheme

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!