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

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

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

Code Fragment 7.3:<br />

Method depth written <strong>in</strong> <strong>Java</strong>.<br />

The runn<strong>in</strong>g time of algorithm depth(T, v) is O(d v ), where d v denotes the depth of<br />

the node v <strong>in</strong> the tree T, because the algorithm performs a constant-time recursive<br />

step for each ancestor of v. Thus, algorithm depth (T, v) runs <strong>in</strong> O(n) worst-case<br />

time, where n is the total number of nodes of T, s<strong>in</strong>ce a node of T may have depth n<br />

− 1 <strong>in</strong> the worst case. Although such a runn<strong>in</strong>g time is a function of the <strong>in</strong>put size, it<br />

is more accurate to characterize the runn<strong>in</strong>g time <strong>in</strong> terms of the parameter d v , s<strong>in</strong>ce<br />

this parameter can be much smaller than n.<br />

Height<br />

The height of a node v <strong>in</strong> a tree T is also def<strong>in</strong>ed recursively:<br />

• If v is an external node, then the height of v is 0<br />

• Otherwise, the height of v is one plus the maximum height of a child of v.<br />

The height of a nonempty tree T is the height of the root of T. For example, the<br />

tree of Figure 7.2 has height 4. In addition, height can also be viewed as follows.<br />

Proposition 7.4: The height of a nonempty tree T is equal to the maximum<br />

depth of an external node of T.<br />

We leave the justification of this fact to an exercise (R-7.6). We present here an<br />

algorithm, height1, shown <strong>in</strong> Code Fragment 7.4 <strong>and</strong> implemented <strong>in</strong> <strong>Java</strong> <strong>in</strong><br />

Code Fragment 7.5, for comput<strong>in</strong>g the height of a nonempty tree T based on the<br />

proposition above <strong>and</strong> the algorithm depth from Code Fragment 7.2.<br />

385

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

Saved successfully!

Ooh no, something went wrong!