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

key: INTEGER; left, right: Node<br />

END;<br />

VAR R: Texts.Reader; W: Texts.Writer; root: Node;<br />

PROCEDURE tree (n: INTEGER): Node;<br />

VAR new: Node;<br />

x, nl, nr: INTEGER;<br />

BEGIN (*construct perfectly balanced tree with n nodes*)<br />

IF n = 0 THEN new := NIL<br />

ELSE nl := n DIV 2; nr := n-nl-1;<br />

NEW(new); Texts.ReadInt(R, new.key);<br />

new.key := x; new.left := tree(nl); new.right := tree(nr)<br />

END;<br />

RETURN new<br />

END tree;<br />

PROCEDURE PrintTree (t: Node; h: INTEGER);<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;<br />

Assume, for example, the following input data for a tree with 21 nodes:<br />

8 9 11 15 19 20 21 7 3 2 1 5 6 4 13 14 10 12 17 16 18<br />

The call root := tree(21) reads the input dara while constructing the perfectly balanced tree shown in Fig.<br />

4.23.<br />

8<br />

9 5<br />

11 7<br />

6 12<br />

15 20<br />

3 1<br />

4 14<br />

17 18<br />

19<br />

21<br />

2<br />

13<br />

10<br />

16<br />

Fig. 4.23. Tree generated by preceding program<br />

Note the simplicity <strong>and</strong> transparency of this program that is obtained through the use of recursive<br />

procedures. It is obvious that recursive algorithms are particularly suitable when a program is to manipulate<br />

information whose structure is itself defined recursively. This is again manifested in the procedure which

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

Saved successfully!

Ooh no, something went wrong!