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: 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,


slide-1
SLIDE 1

Today’s announcements:

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

Today’s Plan

◮ Binary Search Trees

Warm up: Are these BSTs? 5 4 1 3 8 7 11 9 5 2 4 7 8 11 10 15 18 20 21

1 / 7

slide-2
SLIDE 2

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?

2 / 7

slide-3
SLIDE 3

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.

3 / 7

slide-4
SLIDE 4

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

slide-5
SLIDE 5

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

slide-6
SLIDE 6

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

slide-7
SLIDE 7

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; }

Remove a node from a Binary Search Tree

7 / 7