Today’s announcements: ◮ MT1 Oct 10, 19:00-21:00 CIRS 1250 Today’s Plan ◮ Binary Search Trees Warm up: Are these BSTs? 9 5 5 11 4 8 2 7 8 10 18 1 7 11 4 15 20 3 21 1 / 7
Finding a Node Node *& pfind(K & key, Node *& r) { if (r == NULL) return r; if (key < r->key) return pfind(key, r->left); 10 Chiro if (key > r->key) 5 15 return pfind(key, r->right); Shiro Tora return r; 2 9 20 } Kuro Kai Hime 7 17 30 Runtime? Fuku Rin Minto 2 / 7
Insert void pinsert(K & key, D & data, Node *& root) { Node *& target = pfind(key, root); if( target != NULL) { cerr<<"Duplicate:"<<key<<"\n"; 10 Chiro } 5 15 target = new Node(key, data); Shiro Tora } 2 9 20 Kuro Kai Hime 7 17 30 Fuku Rin Minto One reason to have the *& version of pfind . 3 / 7
Multiple inserts into a BST What BST results from inserting into an empty BST: ◮ � 1 , Momo � , � 2 , Kuro � , � 3 , Hana � , � 4 , Koko � , � 5 , Shiro � , � 6 , Sora � , � 7 , Fuku � ◮ � 7 , Fuku � , � 6 , Sora � , � 5 , Shiro � , � 4 , Koko � , � 3 , Hana � , � 2 , Kuro � , � 1 , Momo � ◮ � 4 , Koko � , � 2 , Kuro � , � 6 , Sora � , � 1 , Momo � � 3 , Hana � , � 5 , Shiro � , � 7 , Fuku � , How long do these take? 4 / 7
Average depth in a BST Choose a binary tree with n nodes, 1. equally likely from all n node binary trees: Average depth is Θ( √ n ). 2. by inserting n items in random order into an empty BST: Average depth is Θ(log n ). 5 / 7
Find node with minimum key in BST Node *& findMin(Node *& root) { if( root == NULL || root->left == NULL ) return root; return findMin(root->left); } 6 / 7
Remove a node from a Binary Search Tree void remove(KType key, Node *& root) { Node *& handle= pfind(key, root); if (handle == NULL) return; Node * toDelete = handle; if (handle->left == NULL) {// Leaf or only right child handle = handle->right; } else if (handle->right == NULL) { // Only left child handle = handle->left; } else { // Two children Node *& succ = findMin(handle->right); handle->key = succ->key; toDelete = succ; succ = succ->right; // succ has no left child } delete toDelete; } 7 / 7
Recommend
More recommend