lecture21

lecture21 - COMP 250 Winter 2010 21 - binary search trees 2...

This preview shows pages 1–2. Sign up to view the full content.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: COMP 250 Winter 2010 21 - binary search trees 2 March 5, 2010 Removing a node from a binary search tree The last operation we consider on binary search trees is to remove a node. Here is a recursive algorithm for doing it. remove(root, key){ if( root == null ) return null else if ( key &lt; root.key ) (**) root.left = remove( root.left, key ) else if ( key &gt; root.key ) (**) root.right = remove( root.right, key) else if root.left == null (*) return root.right else if root.right == null return root.left else{ root.key = findMin( root.right ).key; root.right = remove( root.right, root.key ); } return root; } Note the argument root is only the root of the BST in the first call of the method. In subsequent (recursive) calls, root is the root of a subtree. There are a few subtleties in the algorithm that need explaining. Lets consider different cases: The node to be removed is a leaf. In this case, we could find the parent of the node (assuming there is a parent) and replace the parents child reference to the node with a null reference. This is easy to do if we have a parent reference at each node (similar to removing the tail element of a doubly linked list)....
View Full Document

This note was uploaded on 09/25/2011 for the course COMP 250 taught by Professor Blanchette during the Spring '08 term at McGill.

Page1 / 3

lecture21 - COMP 250 Winter 2010 21 - binary search trees 2...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online