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.4: Algorithm height1 for<br />

comput<strong>in</strong>g the height of a nonempty tree T. Note that<br />

this algorithm calls algorithm depth (Code Fragment<br />

7.2).<br />

Code Fragment 7.5: Method height1 written <strong>in</strong><br />

<strong>Java</strong>. Note the use of the max method of class<br />

java.lang. Math.<br />

Unfortunately, algorithm height1 is not very efficient. S<strong>in</strong>ce height1 calls<br />

algorithm depth (v) on each external node v of T, the runn<strong>in</strong>g time of height1 is<br />

given by O(n + Σ v (1 + d v )), where n is the number of nodes of T, d v is the depth<br />

of node v, <strong>and</strong> E is the set of external nodes of T. In the worst case, the sumΣ v (1 +<br />

dv) is proportional to n 2 . (See Exercise C-7.6.) Thus, algorithm height1 runs <strong>in</strong><br />

O(n 2 ) time.<br />

Algorithm height2, shown <strong>in</strong> Code Fragment 7.6 <strong>and</strong> implemented <strong>in</strong> <strong>Java</strong> <strong>in</strong><br />

Code Fragment 7.7, computes the height of tree T <strong>in</strong> a more efficient manner by<br />

us<strong>in</strong>g the recursive def<strong>in</strong>ition of height.<br />

386

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

Saved successfully!

Ooh no, something went wrong!