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.

10.1.1 Search<strong>in</strong>g<br />

To perform operation f<strong>in</strong>d(k) <strong>in</strong> a dictionary D that is represented with a b<strong>in</strong>ary<br />

search tree T, we view the tree T as a decision tree (recall Figure 7.10). In this case,<br />

the question asked at each <strong>in</strong>ternal node v of T is whether the search key k is less<br />

than, equal to, or greater than the key stored at node v, denoted with key(v). If the<br />

answer is "smaller," then the search cont<strong>in</strong>ues <strong>in</strong> the left subtree. If the answer is<br />

"equal," then the search term<strong>in</strong>ates successfully. If the answer is "greater," then the<br />

search cont<strong>in</strong>ues <strong>in</strong> the right subtree. F<strong>in</strong>ally, if we reach an external node, then the<br />

search term<strong>in</strong>ates unsuccessfully. (See Figure 10.1.)<br />

Figure 10.1: (a) A b<strong>in</strong>ary search tree T represent<strong>in</strong>g a<br />

dictionary D with <strong>in</strong>teger keys; (b) nodes of T visited<br />

when execut<strong>in</strong>g operations f<strong>in</strong>d(76) (successful) <strong>and</strong><br />

f<strong>in</strong>d(25) (unsuccessful) on D. For simplicity, we show<br />

keys but entry values.<br />

We describe this approach <strong>in</strong> detail <strong>in</strong> Code Fragment 10.1. Given a search key k<br />

<strong>and</strong> a node v of T, this method, TreeSearch, returns a node (position) w of the<br />

subtree T(v) of T rooted at v, such that one of the follow<strong>in</strong>g occurs:<br />

• w is an <strong>in</strong>ternal node <strong>and</strong> w's entry has key equal to k.<br />

• w is an external node represent<strong>in</strong>g k's proper place <strong>in</strong> an <strong>in</strong>order traversal<br />

of T(v), but k is not a key conta<strong>in</strong>ed <strong>in</strong> T(v).<br />

Thus, method f<strong>in</strong>d(k) can be performed by call<strong>in</strong>g TreeSearch(k, T.root()).<br />

Let w be the node of T returned by this call. If w is an <strong>in</strong>ternal node, then we return<br />

w's entry; otherwise, we return null.<br />

Code Fragment 10.1:<br />

search tree.<br />

Recursive search <strong>in</strong> a b<strong>in</strong>ary<br />

585

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

Saved successfully!

Ooh no, something went wrong!