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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Example 7.6: The preorder traversal of the tree associated with a document, as<br />

<strong>in</strong> Example 7.3, exam<strong>in</strong>es an entire document sequentially, from beg<strong>in</strong>n<strong>in</strong>g to end.<br />

If the external nodes are removed before the traversal, then the traversal exam<strong>in</strong>es<br />

the table of contents of the document. (See Figure 7.6.)<br />

The preorder traversal is also an efficient way to access all the nodes of a tree. To<br />

justify this, let us consider the runn<strong>in</strong>g time of the preorder traversal of a tree T with<br />

n nodes under the assumption that visit<strong>in</strong>g a node takes O(1) time. The analysis of<br />

the preorder traversal algorithm is actually similar to that of algorithm height2<br />

(Code Fragment 7.7), given <strong>in</strong> Section 7.2.1. At each node v, the nonrecursive part<br />

of the preorder traversal algorithm requires time O(1 + c v ), where c v is the number<br />

of children of v. Thus, by Proposition 7.5, the overall runn<strong>in</strong>g time of the preorder<br />

traversal of T is O(n).<br />

Algorithm toStr<strong>in</strong>gPreorder(T, v), implemented <strong>in</strong> <strong>Java</strong> <strong>in</strong> Code<br />

Fragment 7.9, performs a preorder pr<strong>in</strong>t<strong>in</strong>g of the subtree of a node v of T, that is, it<br />

performs the preorder traversal of the subtree rooted at v <strong>and</strong> pr<strong>in</strong>ts the element<br />

stored at a node when the node is visited. Recall that, for an ordered tree T, method<br />

T.children(v) returns an iterable collection that accesses the children of v <strong>in</strong><br />

order.<br />

Code Fragment 7.9: Method toStr<strong>in</strong>gPreorder(T, v)<br />

that performs a preorder pr<strong>in</strong>t<strong>in</strong>g of the elements <strong>in</strong> the<br />

subtree of node v of T.<br />

389

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

Saved successfully!

Ooh no, something went wrong!