1 Joe Meehean.  Important and common problem  Given a collection, determine whether value v is a member  Common variation given a collection of unique.

Slides:



Advertisements
Similar presentations
Comp 122, Spring 2004 Binary Search Trees. btrees - 2 Comp 122, Spring 2004 Binary Trees  Recursive definition 1.An empty tree is a binary tree 2.A node.
Advertisements

S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
Tree Data Structures &Binary Search Tree 1. Trees Data Structures Tree  Nodes  Each node can have 0 or more children  A node can have at most one parent.
Binary Search Trees Azhar Maqsood School of Electrical Engineering and Computer Sciences (SEECS-NUST)
Binary Search Trees. John Edgar  Understand tree terminology  Understand and implement tree traversals  Define the binary search tree property  Implement.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
They’re not just binary anymore!
Binary Search Trees Briana B. Morrison Adapted from Alan Eugenio.
Data Structures: Trees i206 Fall 2010 John Chuang Some slides adapted from Marti Hearst, Brian Hayes, or Glenn Brookshear.
Department of Computer Science University of Maryland, College Park
Trees, Binary Trees, and Binary Search Trees COMP171.
1 Trees. 2 Outline –Tree Structures –Tree Node Level and Path Length –Binary Tree Definition –Binary Tree Nodes –Binary Search Trees.
BST Data Structure A BST node contains: A BST contains
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
Data Structures Using C++ 2E Chapter 11 Binary Trees and B-Trees.
1 BST Trees A binary search tree is a binary tree in which every node satisfies the following: the key of every node in the left subtree is.
Properties: -Each node has a value -The left subtree contains only values less than the parent node’s value -The right subtree contains only values greater.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Chapter 19 - basic definitions - order statistics ( findkth( ) ) - balanced binary search trees - Java implementations Binary Search Trees 1CSCI 3333 Data.
Data Structures - CSCI 102 Binary Tree In binary trees, each Node can point to two other Nodes and looks something like this: template class BTNode { public:
Sorted Array What is BigO for sorted list implemented as: ArrayList: – Search : – Insert(value) : – Remove(value) : LinkedList: – Search : – Insert(value)
Recursion Bryce Boe 2013/11/18 CS24, Fall Outline Wednesday Recap Lab 7 Iterative Solution Recursion Binary Tree Traversals Lab 7 Recursive Solution.
Chapter 19: Binary Trees. Objectives In this chapter, you will: – Learn about binary trees – Explore various binary tree traversal algorithms – Organize.
AITI Lecture 20 Trees, Binary Search Trees Adapted from MIT Course 1.00 Spring 2003 Lecture 28 and Tutorial Note 10 (Teachers: Please do not erase the.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
INTRODUCTION TO BINARY TREES P SORTING  Review of Linear Search: –again, begin with first element and search through list until finding element,
1 Joe Meehean.  BST efficiency relies on height lookup, insert, delete: O(height) a balanced tree has the smallest height  We can balance an unbalanced.
BINARY SEARCH TREE. Binary Trees A binary tree is a tree in which no node can have more than two children. In this case we can keep direct links to the.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
1 Chapter 10 Trees. 2 Definition of Tree A tree is a set of linked nodes, such that there is one and only one path from a unique node (called the root.
Trees, Binary Trees, and Binary Search Trees COMP171.
Binary Search Trees (10.1) CSE 2011 Winter November 2015.
Binary Search Tree Traversal Methods. How are they different from Binary Trees?  In computer science, a binary tree is a tree data structure in which.
Trees  Linear access time of linked lists is prohibitive Does there exist any simple data structure for which the running time of most operations (search,
 Trees Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
Red–black trees.  Define the red-black tree properties  Describe and implement rotations  Implement red-black tree insertion  We will skip red-black.
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
Lecture1 introductions and Tree Data Structures 11/12/20151.
1 Joe Meehean.  We wanted a data structure that gave us... the smallest item then the next smallest then the next and so on…  This ADT is called a priority.
Binary Search Trees (BSTs) 18 February Binary Search Tree (BST) An important special kind of binary tree is the BST Each node stores some information.
CS 367 Introduction to Data Structures Lecture 7.
Binary Tree. Some Terminologies Short review on binary tree Tree traversals Binary Search Tree (BST)‏ Questions.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
Binary Search Trees (BST)
Tree Data Structures. Heaps for searching Search in a heap? Search in a heap? Would have to look at root Would have to look at root If search item smaller.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
Binary Search Trees.  Understand tree terminology  Understand and implement tree traversals  Define the binary search tree property  Implement binary.
1 Joe Meehean. A A B B D D I I C C E E X X A A B B D D I I C C E E X X  Terminology each circle is a node pointers are edges topmost node is the root.
Trees By JJ Shepherd. Introduction Last time we discussed searching and sorting in a more efficient way Divide and Conquer – Binary Search – Merge Sort.
8/3/2007CMSC 341 BTrees1 CMSC 341 B- Trees D. Frey with apologies to Tom Anastasio.
(c) University of Washington20c-1 CSC 143 Binary Search Trees.
BSTs, AVL Trees and Heaps Ezgi Shenqi Bran. What to know about Trees? Height of a tree Length of the longest path from root to a leaf Height of an empty.
1 Trees 3: The Binary Search Tree Reading: Sections 4.3 and 4.6.
Binary Search Tree (BST)
Binary Trees, Binary Search Trees
Chapter 20: Binary Trees.
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Trees 3: The Binary Search Tree
Chapter 21: Binary Trees.
AVL Trees CENG 213 Data Structures.
Lec 12 March 9, 11 Mid-term # 1 (March 21?)
Find in a linked list? first last 7  4  3  8 NULL
CMSC 341 Binary Search Trees.
Binary Trees, Binary Search Trees
CMSC 341 Binary Search Trees.
CSC 143 Binary Search Trees.
Trees.
Binary Trees, Binary Search Trees
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

1 Joe Meehean

 Important and common problem  Given a collection, determine whether value v is a member  Common variation given a collection of unique keys, each associated with a value find value v associated with the key k find the mapping

 Dictionary key => word value => definition  Phonebook key => name value => phone number  Webpage key => address value => html files and pictures

 Problem: given an array of N values, determine if v in one of them  Two approaches sequential search binary search

 Look at each value in turn (iterate) e.g., a[0], a[1], … quit when v is found or end of array reached worst case time: O(N)  What if a is sorted? look at each value in turn quit when v is found or end of array reached OR, when current value is > v worst case time still O(N)

 Array must be sorted (a[0] <= a[1] <= a[2] … <= a[n])  Algorithm like the Clock Game on Price is RightClock Game

 Array must be sorted (a[0] <= a[1] <= a[2] … <= a[n])  Algorithm look at middle value x in array if x == v else eliminate ½ the array  if v < x, eliminate the right half  if v > x, eliminate the left half repeat until v is found or no remaining values

 Array or vector must be sorted  Data type must provide < operator if !(a < b) && !(b < a) then b == a  Or Comparator

 Number of times N can be divided by 2  In Big O it is O(logN) difference between log 2 N and log N is a constant  Scales better than O(N) O(logN) algorithms are faster  If N = 1024, log(N) is 10 9

11 ant bar Throws away half the entries at every compare bat cat dog elk fox owl rat ant bat cat dog elk fox owl rat ant bat cat dog elk fox owl rat ant bat cat dog elk fox owl rat

12 What if we made a special data structure that represents a binary search?

 Special kind of binary tree  Each node stores a key sometimes an associated value  For each node n all keys in n’s left subtree are < key at n all keys in n’s right subtree are > key at n if duplicate keys allowed  keys that equal n can go left XOR right (not both) 13

 Insert a key (and associated data)  Lookup a key (and associated data)  Remove a key (…)  Print all keys in sorted order using an inorder traversal 14

Yes In order traversal produces: No: 7 is not <

// private inner class of BST class BinaryNode{ public: K key_; BinaryNode * left_; BinaryNode * right_; //constructors } 16

template > class BST { private: BinaryNode* root_; Compare isLessThan_; public: BST() {root_ = NULL;} bool insert(const K& key); bool lookup(const K& key); void delete(const K& key); } 17

18

 Key is in BST if it is in the root the left subtree or the right subtree  Don’t need to look in both subtrees just like binary search in an array 19

// public driver method // method of BST bool lookup(K& key){ // private recursive helper method // on next slide return lookup(root, key); } 20

// private method of BST bool lookup(Bnode* n, K& k){ if( n == NULL ) return false; else if( isLessThan(k, n->key) ) return lookup(n->left, k); else if( isLessThan(n->key, k)) return lookup(n->right, k); else return true; } 21

 Cases empty (null) subtree value found next look left next look right  Shout it out lookup(4) lookup(5) lookup(3)

 Always follows path from root down  Worst-case goes to a leaf along longest path proportional to tree height  Height related to size given size, how can we know height? 23

 Best case tree is balanced all non-leaf nodes have 2 children all leaves at the same depth height is log 2 N  Worst case tree is linear all non-leaf nodes have a single child height is N 24

lookup(2 )

lookup(2 ) 2 2 Eliminates half the nodes at every compare

lookup(2 ) 2 2 Eliminates half the nodes at every compare

lookup(2 ) 2 2 Eliminates half the nodes at every compare

 Worst-case O(height of tree)  Worst of worst height is N lookup is O(N)  Best worst-case height is log 2 N lookup is O(logN)  O(LogN) is waaaay better than O(N) 29

30

 New values inserted as leaves  Must choose position to respect BST ordering and to ensure we can find it with a lookup  Duplicate keys are not allowed 31

 Traverse the tree like a lookup  If we find a duplicate return an error  If we end up at a null (child of a leaf) make a new node with the key make it the child of the leaf  Note the above two were our base cases for lookup too 32

// members of BST void insert(const K& key){ insert(root, k); } void insert( BinaryNode*& n, const K& key){ if( n == NULL ){ n = new BinaryNode(key); }else if( isLessThan(k, n->key_) ){ insert(k, n->left_); }else if( isLessThan(n->key_, k) ){ insert(k, n->right_); }else{ //duplicate, do nothing } 33

 First names BST You add your names CLASS ACTIVITY 34

 Similar to lookup worst-case follow path from root to leaf O(logN) for a balanced tree O(N) for a completely unbalanced tree 35

 Find the node n w/ key to be deleted  Different actions depending on n’s # of kids Case 1: n has 0 kids (it’s a leaf)  set parent’s n-pointer (left or right) to null Case 2: n has 1 kid  set parent’s n-pointer to point to n’s only kid Case 3: n has 2 kids  replace n’s key with a key further down in the tree  delete that node 36

 What node value can replace n’s value? new value of n must be: > all values in left subtree < all values in right subtree  Largest value from the left subtree  Smallest value from the right subtree let’s choose this one (arbitrarily) use findMin on root of right subtree 37

… … … … delete(17) 38

… … … … 39 delete(17) 17

… … … … delete(16) 40

… … … … delete(16) 41

… … … … Smallest value in right subtree delete(15) 42

… … … … 43 Case 2: 1 kid Replace 16 with it’s only child delete(15)

… … … … 44 Case 2: 1 kid Replace 16 with it’s only child delete(15)

45

 Find the node n w/ key to be deleted  Different actions depending on n’s # of kids case 1: n has 0 kids (it’s a leaf)  set parent’s n-pointer (left or right) to null case 2: n has 1 kid  set parent’s n-pointer to point to n’s only kid case 3: n has 2 kids  replace n’s key with a key further down in the tree  delete that node 46

 Case 1 (n is leaf) and case 2 (n has 1 kid) both need to update the parents pointer  How?  Pass a reference to that pointer 47

// publicly visible method void BST ::delete(const K& key){ delete(root_, key); } // private helper method void BST ::delete( Node*& n, const K& k){ // base case 1 (key not in tree) if( n == null ){ return; }... } 48

// private helper method void BST ::delete( Node*& n, const K& k){... if( isLessThan(k, n->key) ){ delete(n->left, k); }else if( isLessThan(n->key, k) ){ delete(n->right, k); }... } 49

// private helper method void BST ::delete( Node*& n, const K& k){... // case 3 (has two children) else if( n->left != NULL && n->right != NULL ){ Node** tmp = findMin(&n->right); n->key = (*tmp)->key; // handles cases 1 & 2 for tmp removeNodeSimple(*tmp); }... } 50

// private helper method void BST ::delete( Node*& n, const K& k){... else{ // handles cases 1 & 2 removeNodeSimple(n); }... } 51

// private helper method // should only be called on nodes with // 0 or 1 children void removeNodeSimple(Node*& n){ // left as an exercise } 52

 Find the node to be deleted follow path from root to desired node  Delete node worst-case: 2 kids find smallest key in right subtree 53

 Worst-case (delete root)  Root to leaf  H = Height of Tree O(H)  Balanced tree O(logN) where N is keys in tree  O(N) for a completely unbalanced tree 54

 Some BSTs have two data values a key: used to lookup a value: some data associated with that key used to implement maps 55

 In this case: two generic types binary node has four member variables insert has two parameters lookup returns value for given key delete might return value too class BST K key_; V value_; Bnode* left_; Bnode* right_; insert( const K& key, const V& value); V& lookup(const K& key); V delete(const K& key); 56

 BSTs store comparable keys and associated values if desired  Lookup, insert, delete are easy to implement (sort of)  All are worst-case O(Height of tree) O(N) for unbalanced O(logN) for balanced O(logN) is waaaaay better than O(N)  If only we could guarantee a tree was balanced… 57

58