Download presentation
Presentation is loading. Please wait.
1
CS 206 Introduction to Computer Science II 02 / 18 / 2009 Instructor: Michael Eckmann
2
Michael Eckmann - Skidmore College - CS 206 - Spring 2009 Today’s Topics Questions/comments Binary Search trees Remove maximum key Delete a key
3
Remove Maximum Key in a BST Let's consider how to do this. This is equivalent to finding the rightmost node and removing it. Consider several cases.
4
Remove rightmost node in a binary tree To remove the rightmost node in any binary tree –Case 0) if the rightmost node is the root of the tree, do what? –Case 1) If the rightmost node has no left child, then it is a leaf, so you can simply do rightmost.parent.right = null to remove it –Case 2) If the rightmost node has a left child i.e. (rightmost.left != null), then move the whole left subtree to where the current rightmost node is. That is, do rightmost.parent.right = rightmost.left AND set the parent rightmost.left.parent = rightmost.parent We will have to do more than this if we are looking to remove the RM in an arbitrary subtree of a tree.
5
Delete a key in a BST First, start with currNode = root Go down the tree until currNode.key == searchkey. Each step down the tree change currNode to be either the left or right child. So, when the above step is done, we have currNode.parent as the parent and currNode as the node to delete. There are several cases to consider –1) if searchkey was not found –2) currNode == root and currNode.left == null –3) currNode != root and currNode.left == null –4) currNode.left != null
6
Delete a key in a BST Case 1) if searchkey was not found, do nothing --- done. Case 2) currNode == root and currNode.left == null –Set the root to be root.right, AND then as long as the root is not null right now, do root.parent = null, done.
7
Delete a key in a BST Case 3) currNode != root and currNode.left == null –Do we care whether currNode is a left or right child of its parent?
8
Delete a key in a BST Case 3) currNode != root and currNode.left == null –Do we care whether currNode is a left or right child of its parent? –YES –if the currNode is its parent's left child then currNode.parent.left = currNode.right –if the currNode is its parent's right child then currNode.parent.right = currNode.right Case 4) currNode.left != null –This is the hard one. Why? –Let's consider a couple of possible solutions
9
Delete a key in a BST Case 4) currNode != root and currNode.left != null –We'll look at the left subtree of currNode and find it's rightMost node, store it in lstrmn (left subtree's rightmost node). –Then we can a) set currNode.key = lstrmn.key b) remove the node lstrmn from the tree by calling removeRightmost(currNode)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.