12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

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

Sec. 5.4 Binary Search Trees 173120374224427 4273240422 3221202437(a)Figure 5.13 Two Binary Search Trees for a collection of values. Tree (a) resultsif values are inserted in the order 37, 24, 42, 7, 2, 40, 42, 32, 120. Tree (b) resultsif the same values are inserted in the order 120, 42, 42, 7, 2, 32, 37, 24, 40.Figure 5.14 shows a class declaration for the BST that implements the dictionaryADT. The public member functions include those required by the dictionaryADT, along with a construc<strong>to</strong>r <strong>and</strong> destruc<strong>to</strong>r.To find a record with key value K in a BST, begin at the root. If the root s<strong>to</strong>resa record with key value K, then the search is over. If not, then we must searchdeeper in the tree. What makes the BST efficient during search is that we needsearch only one of the node’s two subtrees. If K is less than the root node’s keyvalue, we search only the left subtree. If K is greater than the root node’s keyvalue, we search only the right subtree. This process continues until a record withkey value K is found, or we reach a leaf node. If we reach a leaf node withoutencountering K, then no record exists in the BST whose key value is K.Example 5.5 Consider searching for the node with key value 32 in thetree of Figure 5.13(a). Because 32 is less than the root value of 37, thesearch proceeds <strong>to</strong> the left subtree. Because 32 is greater than 24, we searchin 24’s right subtree. At this point the node containing 32 is found. Ifthe search value were 35, the same path would be followed <strong>to</strong> the nodecontaining 32. Because this node has no children, we know that 35 is notin the BST.Notice that in Figure 5.14, public member function find calls a private memberfunction named findhelp. Method find takes the search key as an explicitparameter <strong>and</strong> its BST as an implicit parameter, along with space <strong>to</strong> place a copy of(b)40

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

Saved successfully!

Ooh no, something went wrong!