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

today s announcements
SMART_READER_LITE
LIVE PREVIEW

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


slide-1
SLIDE 1

Today’s announcements:

◮ MT1 Oct 10, 19:00-21:00 CIRS 1250

Today’s Plan

◮ Binary Search Trees

Warm up: Level (Depth) order

e b f c a h i d g j 1 2 3 4

void levelOrder( ) { If( root == NULL) return; }}

1 / 8

slide-2
SLIDE 2

Binary Search Trees

Dictionary ADT

Operations

◮ insert ◮ remove ◮ find

key value (data) Multics MULTiplexed Information and Computing Service Unix Uniplexed Multics BSD Berkeley Software Distribution GNU GNU’s Not Unix

◮ insert(Linux, Linus Torvald’s Unix) ◮ find(Unix) returns “Uniplexed Multics”

2 / 8

slide-3
SLIDE 3

Dictionary ADT Implementations

Worst Case time insert find remove (after find) Linked list Unsorted array Sorted array

3 / 8

slide-4
SLIDE 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 4 8 12 14 20 21 25 20 25 14

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

slide-5
SLIDE 5

Binary Search Tree as Dictionary Data Structure

2 8 5 20 17 9 7 14 12 25 21 4

Kai Kuro Shiro Mei Koko Fuku Mikan Sakura Rin Hime Kinako Maru

Binary tree property

◮ each node has ≤ 2 children

Search tree property

For all nodes x,

◮ 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

slide-6
SLIDE 6

Dictionary ADT: BST implementation

2 9 5 20 15 10 7 30 17

Chiro Shiro Kuro Kai Tora Hime Rin Minto Fuku

template<class K, class D> class Dictionary{ public: //ctors etc. ... private: struct Node { K key; D data; Node * left; Node * right; }; Node * root; ... };

6 / 8

slide-7
SLIDE 7

Finding a Node

2 9 5 20 15 10 7 30 17

Chiro Shiro Kuro Kai Tora Hime Rin Minto Fuku

Node *& pfind(K & key, Node *& r) { if (r == NULL) return r; if (key < r->key) return pfind(key, r->left); if (key > r->key) return pfind(key, r->right); return r; } Runtime?

7 / 8

slide-8
SLIDE 8

Insert

2 9 5 20 15 10 7 30 17

Chiro Shiro Kuro Kai Tora Hime Rin Minto Fuku

void pinsert(K & key, D & data, Node *& root) { Node *& target = pfind(key, root); if( target != NULL) { cerr<<"Duplicate:"<<key<<"\n"; } target = new Node(key, data); } One reason to have the *& version of pfind.

8 / 8