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 name of the postorder traversal comes from the fact that this traversal method<br />

will visit a node v after it has visited all the other nodes <strong>in</strong> the subtree rooted at v.<br />

(See Figure 7.8.)<br />

Figure 7.8:<br />

of Figure 7.6.<br />

Postorder traversal of the ordered tree<br />

The analysis of the runn<strong>in</strong>g time of a postorder traversal is analogous to that of a<br />

preorder traversal. (See Section 7.2.2.) The total time spent <strong>in</strong> the nonrecursive<br />

portions of the algorithm is proportional to the time spent visit<strong>in</strong>g the children of<br />

each node <strong>in</strong> the tree. Thus, a postorder traversal of a tree T with n nodes takes O(n)<br />

time, assum<strong>in</strong>g that visit<strong>in</strong>g each node takes O(1) time. That is, the postorder<br />

traversal runs <strong>in</strong> l<strong>in</strong>ear time.<br />

As an example of postorder traversal, we show a <strong>Java</strong> method<br />

toStr<strong>in</strong>gPostorder <strong>in</strong> Code Fragment 7.12, which performs a postorder<br />

traversal of a tree T. This method pr<strong>in</strong>ts the element stored at a node when it is<br />

visited.<br />

Code Fragment 7.12: Method<br />

toStr<strong>in</strong>gPostorder(T, v) that performs a<br />

postorder pr<strong>in</strong>t<strong>in</strong>g of the elements <strong>in</strong> the subtree of<br />

node v of T. The method implicitly calls toStr<strong>in</strong>g on<br />

elements, when they are <strong>in</strong>volved <strong>in</strong> a str<strong>in</strong>g<br />

concatenation operation.<br />

392

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

Saved successfully!

Ooh no, something went wrong!