26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

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.

1122 Data Structures Chapter 19<br />

Fig. Fig. 19.19 19.19 19.19 A binary search tree.<br />

Method inorderHelper (lines 105–118) defines the steps for an inorder traversal.<br />

Those steps are as follows:<br />

1. Traverse the left subtree with a call <strong>to</strong> inorderHelper (line 111).<br />

2. Process the value in the node (line 114).<br />

3. Traverse the right subtree with a call <strong>to</strong> inorderHelper (line 117).<br />

The inorder traversal does not process the value in a node until the values in that node’s left<br />

subtree are processed. The inorder traversal of the tree in Fig. 19.19 is<br />

6 13 17 27 33 42 48<br />

Note that the inorder traversal of a binary search tree prints the node values in<br />

ascending order. The process of creating a binary search tree actually sorts the data—and<br />

thus, this process is called the binary tree sort.<br />

Method preorderHelper (lines 83–96) defines the steps for a preorder traversal.<br />

Those steps are as follows:<br />

1. Process the value in the node (line 89).<br />

2. Traverse the left subtree with a call <strong>to</strong> preorderHelper (line 92).<br />

3. Traverse the right subtree with a call <strong>to</strong> preorderHelper (line 95).<br />

The preorder traversal processes the value in each node as the node is visited. After processing<br />

the value in a given node, the preorder traversal processes the values in the left subtree,<br />

then the values in the right subtree. The preorder traversal of the tree in Fig. 19.19 is<br />

27 13 6 17 42 33 48<br />

Method pos<strong>to</strong>rderHelper (lines 127–140) defines the steps for a pos<strong>to</strong>rder traversal.<br />

Those steps are as follows:<br />

1. Traverse the left subtree with a pos<strong>to</strong>rderHelper (line 133).<br />

2. Traverse the right subtree with a pos<strong>to</strong>rderHelper (line 136).<br />

3. Process the value in the node (line 139).<br />

The pos<strong>to</strong>rder traversal processes the value in each node after the values of all that node’s<br />

children are processed. The pos<strong>to</strong>rderTraversal of the tree in Fig. 19.19 is<br />

6 17 13 33 48 42 27<br />

27<br />

13 42<br />

6 17 33 48<br />

The binary search tree facilitates duplicate elimination. While building a tree, the insertion<br />

operation recognizes attempts <strong>to</strong> insert a duplicate value, because a duplicate follows

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

Saved successfully!

Ooh no, something went wrong!