23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

eplace<br />

O(1)<br />

root, parent<br />

O(1)<br />

children(v)<br />

O(c v )<br />

isInternal, isExternal, isRoot<br />

O(1)<br />

7.2 Tree Traversal <strong>Algorithms</strong><br />

In this section, we present algorithms for perform<strong>in</strong>g traversal computations on a tree<br />

by access<strong>in</strong>g it through the tree ADT methods.<br />

7.2.1 Depth <strong>and</strong> Height<br />

Let v be a node of a tree T. The depth of v is the number of ancestors of v,<br />

exclud<strong>in</strong>g v itself. For example, <strong>in</strong> the tree of Figure 7.2, the node stor<strong>in</strong>g<br />

International has depth 2. Note that this def<strong>in</strong>ition implies that the depth of the root<br />

of T is 0.<br />

The depth of a node v can also be recursively def<strong>in</strong>ed as follows:<br />

• If v is the root, then the depth of v is 0<br />

• Otherwise, the depth of v is one plus the depth of the parent of v.<br />

Based on this def<strong>in</strong>ition, we present a simple, recursive algorithm, depth, <strong>in</strong> Code<br />

Fragment 7.2, for comput<strong>in</strong>g the depth of a node v <strong>in</strong> T. This method calls itself<br />

recursively on the parent of v, <strong>and</strong> adds 1 to the value returned. A simple <strong>Java</strong><br />

implementation of this algorithm is shown <strong>in</strong> Code Fragment 7.3.<br />

Code Fragment 7.2: Algorithm for comput<strong>in</strong>g the<br />

depth of a node v <strong>in</strong> a tree T.<br />

384

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

Saved successfully!

Ooh no, something went wrong!