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

A<br />

B<br />

C<br />

D E F G H<br />

I<br />

J K L O M N P<br />

Fig. 4.19. Ternary tree extended with special nodes<br />

Of particular importance are the ordered trees of degree 2. They are called binary trees. We define an<br />

ordered binary tree as a finite set of elements (nodes) which either is empty or consists of a root (node)<br />

with two disjoint binary trees called the left <strong>and</strong> the right subtree of the root. In the following sections we<br />

shall exclusively deal with binary trees, <strong>and</strong> we therefore shall use the word tree to mean ordered binary<br />

tree. Trees with degree greater than 2 are called multiway trees <strong>and</strong> are discussed in sect. 4.7.1.<br />

Familiar examples of binary trees are the family tree (pedigree) with a person's father <strong>and</strong> mother as<br />

descendants (!), the history of a tennis tournament with each game being a node denoted by its winner <strong>and</strong><br />

the two previous games of the combatants as its descendants, or an arithmetic expression with dyadic<br />

operators, with each operator denoting a branch node with its oper<strong>and</strong>s as subtrees (see Fig. 4.20).<br />

*<br />

+<br />

-<br />

a<br />

/<br />

d<br />

*<br />

b<br />

c<br />

e<br />

f<br />

Fig. 4.20. Tree representation of expression (a + b/c) * (d – e*f)<br />

We now turn to the problem of representation of trees. It is plain that the illustration of such recursive<br />

structures in terms of branching structures immediately suggests the use of our pointer facility. There is<br />

evidently no use in declaring variables with a fixed tree structure; instead, we define the nodes as variables<br />

with a fixed structure, i.e., of a fixed type, in which the degree of the tree determines the number of pointer<br />

components referring to the node's subtrees. Evidently, the reference to the empty tree is denoted by NIL.<br />

Hence, the tree of Fig. 4.20 consists of components of a type defined as follows <strong>and</strong> may then be<br />

constructed as shown in Fig. 4.21.<br />

TYPE Node = POINTER TO NodeDesc;<br />

TYPE NodeDesc = RECORD op: CHAR; left, right: Node END

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

Saved successfully!

Ooh no, something went wrong!