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.

The simplifications that come from represent<strong>in</strong>g a complete b<strong>in</strong>ary tree T with an<br />

array list aid <strong>in</strong> the implementation of methods add <strong>and</strong> remove. Assum<strong>in</strong>g that no<br />

array expansion is necessary, methods add <strong>and</strong> remove can be performed <strong>in</strong> O(1)<br />

time, for they simply <strong>in</strong>volve add<strong>in</strong>g or remov<strong>in</strong>g the last element of the array list.<br />

Moreover, the array list associated with T has n + 1 elements (the element at <strong>in</strong>dex<br />

0 is a place-holder). If we use an extendable array that grows <strong>and</strong> shr<strong>in</strong>ks for the<br />

implementation of the array list (Section 6.1.4 <strong>and</strong> Exercise C-6.2), the space used<br />

by the array-list representation of a complete b<strong>in</strong>ary tree with n nodes is O(n) <strong>and</strong><br />

operations add <strong>and</strong> remove take O(1) amortized time.<br />

<strong>Java</strong> Implementation of a Complete B<strong>in</strong>ary Tree<br />

We represent the complete b<strong>in</strong>ary tree ADT <strong>in</strong> <strong>in</strong>terface<br />

CompleteB<strong>in</strong>aryTree shown <strong>in</strong> Code Fragment 8.9. We provide a <strong>Java</strong> class<br />

ArrayListCompleteB<strong>in</strong>aryTree that implements the<br />

CompleteB<strong>in</strong>aryTree <strong>in</strong>terface with an array list <strong>and</strong> supports methods add<br />

<strong>and</strong> remove <strong>in</strong> O(1) time <strong>in</strong> Code Fragments 8.10–8.12.<br />

Code Fragment 8.9: Interface CompleteB<strong>in</strong>aryTree<br />

for a complete b<strong>in</strong>ary tree.<br />

Code Fragment 8.10: Class<br />

ArrayListCompleteB<strong>in</strong>aryTree implement<strong>in</strong>g<br />

<strong>in</strong>terface CompleteB<strong>in</strong>aryTree us<strong>in</strong>g a<br />

474

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

Saved successfully!

Ooh no, something went wrong!