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 17937 40247 324240 422120Figure 5.17 An example of removing the value 37 from the BST. The nodecontaining this value has two children. We replace value 37 with the least valuefrom the node’s right subtree, in this case 40./** Remove a node with key value k@return The tree with the node removed */private BSTNode removehelp(BSTNode rt, Key k) {if (rt == null) return null;if (rt.key().compareTo(k) > 0)rt.setLeft(removehelp(rt.left(), k));else if (rt.key().compareTo(k) < 0)rt.setRight(removehelp(rt.right(), k));else { // Found itif (rt.left() == null)return rt.right();else if (rt.right() == null)return rt.left();else { // Two childrenBSTNode temp = getmin(rt.right());rt.setElement(temp.element());rt.setKey(temp.key());rt.setRight(deletemin(rt.right()));}}return rt;}Figure 5.18 Implementation for the BST removehelp method.from the right subtree does not have a similar problem, because it does not violatethe Binary Search Tree Property if equal values appear in the right subtree.From the above, we see that if we want <strong>to</strong> remove the record s<strong>to</strong>red in a nodewith two children, then we simply call deletemin on the node’s right subtree<strong>and</strong> substitute the record returned for the record being removed. Figure 5.18 showsis the code for removehelp.The cost for findhelp <strong>and</strong> inserthelp is the depth of the node found orinserted. The cost for removehelp is the depth of the node being removed, or

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

Saved successfully!

Ooh no, something went wrong!