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

root<br />

*<br />

+<br />

-<br />

NIL<br />

a<br />

NIL<br />

/<br />

NIL<br />

d<br />

NIL<br />

*<br />

NIL<br />

b<br />

NIL<br />

NIL<br />

c<br />

NIL<br />

NIL<br />

e<br />

NIL<br />

NIL<br />

f<br />

NIL<br />

Fig. 4.21. Tree of Fig. 4.21 represented as linked data structure<br />

Before investigating how trees might be used advantageously <strong>and</strong> how to perform operations on trees,<br />

we give an example of how a tree may be constructed by a program. Assume that a tree is to be generated<br />

containing nodes with the values of the nodes being n numbers read from an input file. In order to make the<br />

problem more challenging, let the task be the construction of a tree with n nodes <strong>and</strong> minimal height. In<br />

order to obtain a minimal height for a given number of nodes, one has to allocate the maximum possible<br />

number of nodes of all levels except the lowest one. This can clearly be achieved by distributing incoming<br />

nodes equally to the left <strong>and</strong> right at each node. This implies that we structure the tree for given n as shown<br />

in Fig. 4.22, for n = 1, ... , 7.<br />

n=1 n=2 n=3<br />

n=4 n=5<br />

n=6<br />

n=7<br />

Fig. 4.22. Perfectly balanced trees<br />

The rule of equal distribution under a known number n of nodes is best formulated recursively:<br />

1. Use one node for the root.<br />

2. Generate the left subtree with nl = n DIV 2 nodes in this way.<br />

3. Generate the right subtree with nr = n - nl - 1 nodes in this way.<br />

The rule is expressed as a recursive procedure which reads the input file <strong>and</strong> constructs the perfectly<br />

balanced tree. We note the following definition: A tree is perfectly balanced, if for each node the numbers<br />

of nodes in its left <strong>and</strong> right subtrees differ by at most 1.<br />

TYPE Node = POINTER TO RECORD (* ADenS441_BalancedTree *)

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

Saved successfully!

Ooh no, something went wrong!