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.6: Algorithm height2 for<br />

comput<strong>in</strong>g the height of the subtree of tree T rooted<br />

at a node v.<br />

Code Fragment 7.7:<br />

<strong>Java</strong>.<br />

Method height2 written <strong>in</strong><br />

Algorithm height2 is more efficient than height1 (from Code Fragment 7.4).<br />

The algorithm is recursive, <strong>and</strong>, if it is <strong>in</strong>itially called on the root of T, it will<br />

eventually be called on each node of T. Thus, we can determ<strong>in</strong>e the runn<strong>in</strong>g time<br />

of this method by summ<strong>in</strong>g, over all the nodes, the amount of time spent at each<br />

node (on the nonrecursive part). Process<strong>in</strong>g each node <strong>in</strong> children(v) takes O(c v )<br />

time, where c v denotes the number of children of node v. Also, the while loop<br />

has c v iterations <strong>and</strong> each iteration of the loop takes O(1) time plus the time for<br />

the recursive call on a child of v. Thus, algorithm height2 spends O(1 + c v )<br />

time at each node v, <strong>and</strong> its runn<strong>in</strong>g time is O(Σ v (1 + c v )). In order to complete the<br />

analysis, we make use of the follow<strong>in</strong>g property.<br />

Proposition 7.5: Let T be a tree with n nodes, <strong>and</strong> let c v denote the<br />

number of children of a node v of T. Then, summ<strong>in</strong>g over the vertices <strong>in</strong> T, Σ v c v =<br />

n − 1.<br />

387

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

Saved successfully!

Ooh no, something went wrong!