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 156<br />

the empty subtree. Consider, for example, the binary tree shown in Fig. 4.26 <strong>and</strong> the insertion of the name<br />

Paul. The result is shown in dotted lines in the same picture.<br />

NORMA 2<br />

GEORGE 1<br />

ER 2<br />

NIL<br />

ANN<br />

5 MARY 3 PAUL 1 WALTER 4<br />

NIL<br />

NIL NIL<br />

NIL NIL<br />

NIL NIL<br />

Fig. 4.26. Insertion in ordered binary tree<br />

The search process is formulated as a recursive procedure. Note that its parameter p is a variable<br />

parameter <strong>and</strong> not a value parameter. This is essential because in the case of insertion a new pointer value<br />

must be assigned to the variable which previously held the value NIL. Using the input sequence of 21<br />

numbers that had been used above to construct the tree of Fig. 4.23, the search <strong>and</strong> insertion procedure<br />

yields the binary tree shown in Fig. 4.27, with a call search(k, root) for each key k, where root is a<br />

variable of type Node.<br />

7 9<br />

8<br />

3<br />

2 5<br />

11<br />

10 15<br />

1 4 6<br />

13<br />

19<br />

12<br />

14 17<br />

20<br />

16 18<br />

21<br />

Fig. 4.27. Search tree generated by preceding program<br />

PROCEDURE PrintTree (t: Node; h: INTEGER); (* ADenS443_Tree *)<br />

VAR i: INTEGER;<br />

BEGIN (*print tree t with indentation h*)<br />

IF t # NIL THEN<br />

PrintTree(t.left, h+1);<br />

FOR i := 1 TO h DO Texts.Write(W, TAB) END;<br />

Texts.WriteInt(W, t.key, 6); Texts.WriteLn(W);<br />

PrintTree(t.right, h+1)<br />

END<br />

END PrintTree;

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

Saved successfully!

Ooh no, something went wrong!