25.11.2014 Views

Algorithms and Data Structures

Algorithms and Data Structures

Algorithms and Data Structures

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

(Fig. 4.25). The sentinel may be considered as a common, shared representative of all external nodes by<br />

which the original tree was extended (see Fig. 4.19):<br />

PROCEDURE locate (x: INTEGER; t: Node): Node;<br />

BEGIN<br />

s.key := x; (*sentinel*)<br />

WHILE t.key # x DO<br />

IF t.key < x THEN t := t.right ELSE t := t.left END<br />

END;<br />

RETURN t<br />

END locate<br />

Note that in this case locate(x, t) yields the value s instead of NIL, i.e., the pointer to the sentinel, if no<br />

key with value x is found in the tree with root t.<br />

t<br />

4<br />

2<br />

5<br />

1<br />

3<br />

6<br />

s<br />

Fig. 4.25. Search tree with sentinel<br />

4.4.3 Tree Search <strong>and</strong> Insertion<br />

The full power of the dynamic allocation technique with access through pointers is hardly displayed by<br />

those examples in which a given set of data is built, <strong>and</strong> thereafter kept unchanged. More suitable examples<br />

are those applications in which the structure of the tree itself varies, i.e., grows <strong>and</strong>/or shrinks during the<br />

execution of the program. This is also the case in which other data representations, such as the array, fail<br />

<strong>and</strong> in which the tree with elements linked by pointers emerges as the most appropriate solution.<br />

We shall first consider only the case of a steadily growing but never shrinking tree. A typical example is<br />

the concordance problem which was already investigated in connection with linked lists. It is now to be<br />

revisited. In this problem a sequence of words is given, <strong>and</strong> the number of occurrences of each word has<br />

to be determined. This means that, starting with an empty tree, each word is searched in the tree. If it is<br />

found, its occurrence count is incremented; otherwise it is inserted as a new word (with a count initialized<br />

to 1). We call the underlying task tree search with insertion. The following data type definitions are<br />

assumed:<br />

TYPE Node = POINTER TO RECORD<br />

key, count: INTEGER;<br />

left, right: Node<br />

END<br />

Finding the search path is again straightforward. However, if it leads to a dead end (i.e., to an empty<br />

subtree designated by a pointer value NIL), then the given word must be inserted in the tree at the place of

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

Saved successfully!

Ooh no, something went wrong!