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.

• Methods size() <strong>and</strong> isEmpty() use an <strong>in</strong>stance variable stor<strong>in</strong>g the<br />

number of nodes of T, <strong>and</strong> each take O(1) time.<br />

• The accessor methods root, left, right, sibl<strong>in</strong>g <strong>and</strong> parent take O(1) time.<br />

• Method replace(v,e) takes O(1) time.<br />

• Methods iterator() <strong>and</strong> positions() are implemented by perform<strong>in</strong>g a preorder<br />

traversal of the tree (us<strong>in</strong>g the auxiliary method preorderPositions). The<br />

nodes visited by the traversal are stored <strong>in</strong> a position list implemented by class<br />

NodePositionList (Section 6.2.4) <strong>and</strong> the output iterator is generated with<br />

method iterator() of class NodePositionList. Methods<br />

iterator() <strong>and</strong> positions() take O(n) time <strong>and</strong> methods hasNext() <strong>and</strong><br />

next() of the returned iterators run <strong>in</strong> O(1) time.<br />

• Method children uses a similar approach to construct the returned iterable<br />

collection, but it runs <strong>in</strong> O(1) time, s<strong>in</strong>ce there are at most two children for any<br />

node <strong>in</strong> a b<strong>in</strong>ary tree.<br />

• The update methods <strong>in</strong>sertLeft, <strong>in</strong>sertRight, attach, <strong>and</strong><br />

remove all run <strong>in</strong> O(1) time, as they <strong>in</strong>volve constant-time manipulation of a<br />

constant number of nodes.<br />

Consider<strong>in</strong>g the space required by this data structure for a tree with n nodes, note<br />

that there is an object of class BTNode (Code Fragment 7.15) for every node of<br />

tree T. Thus, the overall space requirement is O(n). Table 7.2 summarizes the<br />

performance of the l<strong>in</strong>ked structure implementation of a b<strong>in</strong>ary tree.<br />

Table 7.2: Runn<strong>in</strong>g times for the methods of an n-<br />

node b<strong>in</strong>ary tree implemented with a l<strong>in</strong>ked structure.<br />

Methods hasNext() <strong>and</strong> next() of the iterators returned<br />

by iterator(), positions().iterator(), <strong>and</strong><br />

children(v).iterator() run <strong>in</strong> O(1) time. The<br />

space usage is O(n).<br />

Operation<br />

Time<br />

size, isEmpty<br />

O(1)<br />

iterator, positions<br />

413

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

Saved successfully!

Ooh no, something went wrong!