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.

Time<br />

size, isEmpty<br />

O(1)<br />

iterator, positions<br />

O(n)<br />

replace<br />

O(1)<br />

root, parent, children, left, right<br />

O(1)<br />

hasLeft, hasRight, isInternal, isExternal, isRoot<br />

O(1)<br />

7.3.6 Traversals of B<strong>in</strong>ary Trees<br />

As with general trees, b<strong>in</strong>ary tree computations often <strong>in</strong>volve traversals.<br />

Build<strong>in</strong>g an Expression Tree<br />

Consider the problem of construct<strong>in</strong>g an expression tree from a fully<br />

parenthesized arithmetic expression of size n. (Recall Example 7.9 <strong>and</strong> Code<br />

Fragment 7.24.) In Code Fragment 7.21, we give algorithm buildExpression<br />

for build<strong>in</strong>g such an expression tree, assum<strong>in</strong>g all arithmetic operations are b<strong>in</strong>ary<br />

<strong>and</strong> variables are not parenthesized. Thus, every parenthesized subexpression<br />

conta<strong>in</strong>s an operator <strong>in</strong> the middle. The algorithm uses a stack S while scann<strong>in</strong>g<br />

the <strong>in</strong>put expression E look<strong>in</strong>g for variables, operators, <strong>and</strong> right parentheses.<br />

• When we see a variable or operator x, we create a s<strong>in</strong>gle-node b<strong>in</strong>ary tree<br />

T, whose root stores x <strong>and</strong> we push T on the stack.<br />

• When we see a right parenthesis, ")", we pop the top three trees from the<br />

stack S, which represent a subexpression (E 1 o E 2 ). We then attach the trees for<br />

E 1 <strong>and</strong> E 2 to the one for o, <strong>and</strong> push the result<strong>in</strong>g tree back on S.<br />

We repeat this until the expression E has been processed, at which time the top<br />

element on the stack is the expression tree for E. The total runn<strong>in</strong>g time is O(n).<br />

417

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

Saved successfully!

Ooh no, something went wrong!