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.

Example 7.9: An arithmetic expression can be represented by a b<strong>in</strong>ary tree<br />

whose external nodes are associated with variables or constants, <strong>and</strong> whose <strong>in</strong>ternal<br />

nodes are associated with one of the operators +, −, ×, <strong>and</strong> /. (See Figure 7.11.)<br />

Each node <strong>in</strong> such a tree has a value associated with it.<br />

• If a node is external, then its value is that of its variable or constant.<br />

• If a node is <strong>in</strong>ternal, then its value is def<strong>in</strong>ed by apply<strong>in</strong>g its operation to the<br />

values of its children.<br />

An arithmetic expression tree is a proper b<strong>in</strong>ary tree, s<strong>in</strong>ce each operator +, −, ×, <strong>and</strong> /<br />

takes exactly two oper<strong>and</strong>s. Of course, if we were to allow for unary operators, like<br />

negation (−), as <strong>in</strong> "−x," then we could have an improper b<strong>in</strong>ary tree.<br />

Figure 7.11: A b<strong>in</strong>ary tree represent<strong>in</strong>g an arithmetic<br />

expression. This tree represents the expression ((((3 + 1)<br />

× 3)/((9 −5) +2)) − ((3 × (7 −4)) + 6)). The value<br />

associated with the <strong>in</strong>ternal node labeled "/" is 2.<br />

396

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

Saved successfully!

Ooh no, something went wrong!