Dictionary ADT Today’s announcements: ◮ MT1 tonight, 7-9:00p WOOD 2 ◮ HW2 out, due Feb 5, 11:59p Today’s Plan ◮ Binary Search Trees key value (data) Multics MULTiplexed Information and Computing Service Dictionary ADT Operations Unix Uniplexed Multics BSD Berkeley Software Distribution ◮ insert GNU GNU’s Not Unix ◮ remove ◮ find ◮ insert(Linux, Linus Torvald’s Unix) ◮ find(Unix) returns “Uniplexed Multics” 1 / 8
Dictionary ADT Implementations remove Worst Case time insert find (after find) Linked list Unsorted array Sorted array 2 / 8
Binary Search in a Sorted Array 2 4 5 7 8 9 12 14 17 20 21 25 2 4 5 7 8 12 14 17 20 21 25 2 4 7 8 12 14 20 21 25 4 8 14 20 25 int bSearch(int A[], int key, int i, int j) { if (j < i) return -1; int m = (i + j) / 2; if (key < A[m]) return bSearch(A, key, i, m-1); else if (key > A[m]) return bSearch(A, key, m+1, j); else return m; } 3 / 8
Binary Search Tree as Dictionary Data Structure 9 Kai 5 17 Binary tree property Shiro Rin 2 8 14 20 ◮ each node has ≤ 2 children Kuro Mei Sakura Hime 4 7 12 25 Search tree property Koko Fuku Mikan Kinako 21 For all nodes x , Maru ◮ all keys in left subtree of x smaller than x ’s key ◮ all keys in right subtree of x larger than x ’s key Result: easy to find any given key 4 / 8
Dictionary ADT: BST implementation 10 Chiro template<class K, class D> 5 15 class Dictionary{ Shiro Tora public: //ctors etc. 2 9 20 Kuro Kai Hime ... private: 7 17 30 Fuku Rin Minto struct Node { K key; D data; Node * left; Node * right; }; Node * root; ... }; 5 / 8
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 6 / 8
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 . 7 / 8
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? 8 / 8
Recommend
More recommend