Upload
roy-montgomery
View
215
Download
0
Embed Size (px)
Citation preview
BSTImp: Insert, Delete
Inserting an Element into a BST
• Search for the position in the tree where the element would be found
• Insert the element in the position– Note: A newly inserted node is a leaf
Inserting an Element into a BST (cont’d)
Inserting an Element into a BST
• Search for the position in the tree where the element would be found
• Insert the element in the position– Note: A newly inserted node is a leaf
Inserting an Element into a BST (cont’d)
Inserting an Element into a BST (cont’d)
Exercise: Write a recursive version of insert
Running Time?
Deleting an Element from a BST
• Algorithm: Find the node to delete, delete it• When deleting a node from a BST, there are 3
cases to consider– The node is a leaf; it has no children. This is the
easiest case to deal with– The node has one child. This case is not
complicated– The node has two children. The most complicated
case
Deleting a Leaf
Deleting a Node with One Child
Deleting a Node with One Child (cont’d)
Deleting a Node with Two Children
• Find the rightmost node in the left subtree (WHY?) and swap data between these 2 nodes
Deleting a Node with Two Children (cont’d)
Delete By Copytemplate<class T>void BST<T>::deleteByCopying(BSTNode<T>*& node) { BSTNode<T> *previous, *tmp = node; if (node->right == 0) // node has no right child; node = node->left; else if (node->left == 0) // node has no left child; node = node->right; else { tmp = node->left; // node has both children; previous = node; // 1. while (tmp->right != 0) { // 2. previous = tmp; tmp = tmp->right; } node->key = tmp->key; // 3. if (previous == node) previous->left = tmp->left; else previous->right = tmp->left; // 4. } delete tmp; // 5.}
3. the predecessor is right below the deleted node
4. When the predecessor is not right below the deleted node, after copying the predecessor to the deleted
notde’s key, need to take care of the predessor’ left, note that the predecessor does not have a right child.
deleteByMergingtemplate<class T>void BST<T>::deleteByMerging(BSTNode<T>*& node) { BSTNode<T> *tmp = node; if (node != 0) { if (!node->right) // node has no right child: its left node = node->left; // child (if any) is attached to its parent; else if (node->left == 0) // node has no left child: its right node = node->right; // child is attached to its parent; else { // be ready for merging subtrees; tmp = node->left; // 1. move left while (tmp->right != 0)// 2. and then right as far as possible; tmp = tmp->right; tmp->right = // 3. establish the link between the node->right; // the rightmost node of the left // subtree and the right subtree; tmp = node; // 4. node = node->left; // 5. } delete tmp; // 6. }}