today s announcements
play

Todays announcements: MT1 Oct 10, 19:00-21:00 CIRS 1250 Todays Plan - PowerPoint PPT Presentation

Todays announcements: MT1 Oct 10, 19:00-21:00 CIRS 1250 Todays Plan Binary Search Trees Warm up: Level (Depth) order void levelOrder( ) { a 1 If( root == NULL) return; c 2 b e 3 d f g j 4 h i }} 1 / 8 Binary Search


  1. Today’s announcements: ◮ MT1 Oct 10, 19:00-21:00 CIRS 1250 Today’s Plan ◮ Binary Search Trees Warm up: Level (Depth) order void levelOrder( ) { a 1 If( root == NULL) return; c 2 b e 3 d f g j 4 h i }} 1 / 8

  2. Binary Search Trees key value (data) Multics MULTiplexed Information and Dictionary ADT Computing Service 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” 2 / 8

  3. Dictionary ADT Implementations remove Worst Case time insert find (after find) Linked list Unsorted array Sorted array 3 / 8

  4. 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; } 4 / 8

  5. 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 5 / 8

  6. 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; ... }; 6 / 8

  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 7 / 8

  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 . 8 / 8

Recommend


More recommend