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 postorder traversal method is useful for solv<strong>in</strong>g problems where we wish to<br />

compute some property for each node v <strong>in</strong> a tree, but comput<strong>in</strong>g that property for v<br />

requires that we have already computed that same property for v's children. Such an<br />

application is illustrated <strong>in</strong> the follow<strong>in</strong>g example.<br />

Example 7.7: Consider a file system tree T, where external nodes represent<br />

files <strong>and</strong> <strong>in</strong>ternal nodes represent directories (Example 7.1). Suppose we want to<br />

compute the disk space used by a directory, which is recursively given by the sum<br />

of:<br />

• The size of the directory itself<br />

• The sizes of the files <strong>in</strong> the directory<br />

• The space used by the children directories.<br />

(See Figure 7.9.) This computation can be done with apostorder traversal of tree T.<br />

After the subtrees of an <strong>in</strong>ternal node v have been traversed, we compute the space<br />

used by v by add<strong>in</strong>g the sizes of the directory v itself <strong>and</strong> of the files conta<strong>in</strong>ed <strong>in</strong> v<br />

to the space used by each <strong>in</strong>ternal child of v, which was computed by the recursive<br />

postorder traversals of the children of v.<br />

A Recursive <strong>Java</strong> Method for Comput<strong>in</strong>g Disk Space<br />

Motivated by Example 7.7, <strong>Java</strong> method diskSpace, shown <strong>in</strong> Code Fragment 7.13,<br />

performs a postorder traversal of a file-system tree T, pr<strong>in</strong>t<strong>in</strong>g the name <strong>and</strong> disk<br />

space used by the directory associated with each <strong>in</strong>ternal node of T. When called on<br />

the root of tree T, diskSpace runs <strong>in</strong> time O(n), where n is the number of nodes of T,<br />

provided the auxiliary methods name <strong>and</strong> size take O(1) time.<br />

Figure 7.9: The tree of Figure 7.3 represent<strong>in</strong>g a file<br />

system, show<strong>in</strong>g the name <strong>and</strong> size of the associated<br />

file/directory <strong>in</strong>side each node, <strong>and</strong> the disk space used<br />

by the associated directory above each <strong>in</strong>ternal node.<br />

393

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

Saved successfully!

Ooh no, something went wrong!