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.

start an Euler tour by <strong>in</strong>itializ<strong>in</strong>g a counter to 0, <strong>and</strong> then <strong>in</strong>crement the counter<br />

each time we visit a node on the left. To determ<strong>in</strong>e the number of descendents of<br />

a node v, we compute the difference between the values of the counter when v is<br />

visited on the left <strong>and</strong> when it is visited on the right, <strong>and</strong> add 1. This simple rule<br />

gives us the number of descendents of v, because each node <strong>in</strong> the subtree rooted<br />

at v is counted between v's visit on the left <strong>and</strong> v's visit on the right. Therefore, we<br />

have an O(n)-time method for comput<strong>in</strong>g the number of descendents of each<br />

node.<br />

Another application of the Euler tour traversal is to pr<strong>in</strong>t a fully parenthesized<br />

arithmetic expression from its expression tree (Example 7.9). Algorithm pr<strong>in</strong>tExpression,<br />

shown <strong>in</strong> Code Fragment 7.27, accomplishes this task by perform<strong>in</strong>g the<br />

follow<strong>in</strong>g actions <strong>in</strong> an Euler tour:<br />

• "On the left" action: if the node is <strong>in</strong>ternal, pr<strong>in</strong>t "("<br />

• "From below" action: pr<strong>in</strong>t the value or operator stored at the node<br />

• "On the right" action: if the node is <strong>in</strong>ternal, pr<strong>in</strong>t ")".<br />

Code Fragment 7.27: An algorithm for pr<strong>in</strong>t<strong>in</strong>g the<br />

arithmetic expression associated with the subtree of<br />

an arithmetic expression tree T rooted at v.<br />

7.3.7 The Template Method Pattern<br />

425

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

Saved successfully!

Ooh no, something went wrong!