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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The <strong>in</strong>order traversal can also be applied to the problem of comput<strong>in</strong>g a draw<strong>in</strong>g<br />

of a b<strong>in</strong>ary tree. We can draw a b<strong>in</strong>ary tree T with an algorithm that assigns x- <strong>and</strong><br />

y-coord<strong>in</strong>ates to a node v of T us<strong>in</strong>g the follow<strong>in</strong>g two rules (see Figure 7.19):<br />

• x(v) is the number of nodes visited before v <strong>in</strong> the <strong>in</strong>order traversal of T<br />

• y(v) is the depth of v <strong>in</strong> T.<br />

In this application, we take the convention common <strong>in</strong> computer graphics that x-<br />

coord<strong>in</strong>ates <strong>in</strong>crease left to right <strong>and</strong> y-coord<strong>in</strong>ates <strong>in</strong>crease top to bottom. So the<br />

orig<strong>in</strong> is <strong>in</strong> the upper left corner of the computer screen.<br />

Figure 7.19: An <strong>in</strong>order draw<strong>in</strong>g of a b<strong>in</strong>ary tree.<br />

The Euler Tour Traversal of a B<strong>in</strong>ary Tree<br />

The tree-traversal algorithms we have discussed so far are all forms of iterators.<br />

Each traversal visits the nodes of a tree <strong>in</strong> a certa<strong>in</strong> order, <strong>and</strong> is guaranteed to<br />

visit each node exactly once. We can unify the tree-traversal algorithms given<br />

above <strong>in</strong>to a s<strong>in</strong>gle framework, however, by relax<strong>in</strong>g the requirement that each<br />

node be visited exactly once. The result<strong>in</strong>g traversal method is called the Euler<br />

tour traversal, which we study next. The advantage of this traversal is that it<br />

allows for more general k<strong>in</strong>ds of algorithms to be expressed easily.<br />

The Euler tour traversal of a b<strong>in</strong>ary tree T can be <strong>in</strong>formally def<strong>in</strong>ed as a "walk"<br />

around T, where we start by go<strong>in</strong>g from the root toward its left child, view<strong>in</strong>g the<br />

edges of T as be<strong>in</strong>g "walls" that we always keep to our left. (See Figure 7.20.)<br />

Each node v of T is encountered three times by the Euler tour:<br />

• "On the left" (before the Euler tour of v's left subtree)<br />

• "From below" (between the Euler tours of v's two subtrees)<br />

• "On the right" (after the Euler tour of v's right subtree).<br />

423

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

Saved successfully!

Ooh no, something went wrong!