170 likes | 278 Views
CSE 326: Data Structures Lecture #8 Pruning (and Pruning for the Lazy). Steve Wolfman Winter Quarter 2000. Today’s Outline. Forming Teams Many Things Steve Didn’t Finish on Friday (BSTs) Binary Search Trees Continued. Successor. Find the next larger node in this node’s subtree.
E N D
CSE 326: Data StructuresLecture #8Pruning (and Pruning for the Lazy) Steve Wolfman Winter Quarter 2000
Today’s Outline • Forming Teams • Many Things Steve Didn’t Finish on Friday (BSTs) • Binary Search Trees Continued
Successor Find the next larger node in this node’s subtree. Node * succ(Node * root) { if (root->right == NULL) return NULL; else return min(root->right); } 10 5 15 2 9 20 17 7 30
Predecessor Find the next smaller node in this node’s subtree. Node * pred(Node * root) { if (root->left == NULL) return NULL; else return max(root->left); } 10 5 15 2 9 20 17 7 30
Deletion 10 5 15 2 9 20 17 7 30 Why might deletion be harder than insertion?
Lazy Deletion • Instead of physically deleting nodes, just mark them as deleted • simpler • physical deletions done in batches • some adds just flip deleted flag • extra memory for deleted flag • many lazy deletions slow finds • some operations may have to be modified (e.g., min and max) 10 5 15 2 9 20 17 7 30
Lazy Deletion Delete(17) Delete(15) Delete(5) Find(9) Find(16) Insert(5) Find(17) 10 5 15 2 9 20 17 7 30
Deletion - Leaf Case Delete(17) 10 5 15 2 9 20 17 7 30
Deletion - One Child Case Delete(15) 10 5 15 2 9 20 7 30
Deletion - Two Child Case Delete(5) 10 5 20 2 9 30 7
Finally… 10 7 20 2 9 30
Delete Code void delete(Comparable key, Node *& root) { Node *& handle(find(key, root)); Node * toDelete = handle; if (handle != NULL) { if (handle->left == NULL) { // Leaf or one child handle = handle->right; delete toDelete; } else if (handle->right == NULL) { // One child handle = handle->left; delete toDelete; } else { // Two child case successor = succ(root); handle->data = successor->data; delete(successor->data, handle->right); } } }
Thinking about Binary Search Trees • Observations • Each operation views two new elements at a time • Elements (even siblings) may be scattered in memory • Binary search trees are fast if they’re shallow • Realities • For large data sets, disk accesses dominate runtime • Some deep and some shallow BSTs exist for any data
Solutions? • Reduce disk accesses? • Keep BSTs shallow?
To Do • Finish Homework #3 • Continue Project II • Read chapter 4 in the book • Read chapters 1-3 and 6 if you haven’t
Coming Up • B-Trees • Self-balancing trees • Third homework assignment due (January 26th) • Second project due (January 31st) • Midterm (February 4th)!