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.

Justification: Each node of T, with the exception of the root, is a child of<br />

another node, <strong>and</strong> thus contributes one unit to the above sum.<br />

By Proposition 7.5, the runn<strong>in</strong>g time of algorithm height2, when called on the<br />

root of T, is O(n), where n is the number of nodes of T.<br />

7.2.2 Preorder Traversal<br />

A traversal of a tree T is a systematic way of access<strong>in</strong>g, or "visit<strong>in</strong>g," all the nodes<br />

of T. In this section, we present a basic traversal scheme for trees, called preorder<br />

traversal. In the next section, we will study another basic traversal scheme, called<br />

postorder traversal.<br />

In a preorder traversal of a tree T, the root of T is visited first <strong>and</strong> then the subtrees<br />

rooted at its children are traversed recursively. If the tree is ordered, then the<br />

subtrees are traversed accord<strong>in</strong>g to the order of the children. The specific action<br />

associated with the "visit" of a node v depends on the application of this traversal,<br />

<strong>and</strong> could <strong>in</strong>volve anyth<strong>in</strong>g from <strong>in</strong>crement<strong>in</strong>g a counter to perform<strong>in</strong>g some<br />

complex computation for v. The pseudo-code for the preorder traversal of the<br />

subtree rooted at a node v is shown <strong>in</strong> Code Fragment 7.8. We <strong>in</strong>itially call this<br />

algorithm with preorder(T,T.root()).<br />

Code Fragment 7.8: Algorithm preorder for<br />

perform<strong>in</strong>g the preorder traversal of the subtree of a<br />

tree T rooted at a node v.<br />

The preorder traversal algorithm is useful for produc<strong>in</strong>g a l<strong>in</strong>ear order<strong>in</strong>g of the<br />

nodes of a tree where parents must always come before their children <strong>in</strong> the<br />

order<strong>in</strong>g. Such order<strong>in</strong>gs have several different applications. We explore a simple<br />

<strong>in</strong>stance of such an application <strong>in</strong> the next example.<br />

Figure 7.6: Preorder traversal of an ordered tree,<br />

where the children of each node are ordered from left<br />

to right.<br />

388

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

Saved successfully!

Ooh no, something went wrong!