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.

Slides:



Advertisements
Similar presentations
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Advertisements

Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
CS 171: Introduction to Computer Science II
Trees, Binary Trees, and Binary Search Trees COMP171.
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (4) Data Structures 11/18/2008 Yang Song.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Fundamentals of Python: From First Programs Through Data Structures
Recursion Bryce Boe 2013/11/18 CS24, Fall Outline Wednesday Recap Lab 7 Iterative Solution Recursion Binary Tree Traversals Lab 7 Recursive Solution.
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
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 ),
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
Trees, Binary Trees, and Binary Search Trees COMP171.
Topic 15 The Binary Search Tree ADT Binary Search Tree A binary search tree (BST) is a binary tree with an ordering property of its elements, such.
Outline Binary Trees Binary Search Tree Treaps. Binary Trees The empty set (null) is a binary tree A single node is a binary tree A node has a left child.
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
Data Structures Chapter 6. Data Structure A data structure is a representation of data and the operations allowed on that data. Examples: 1.Array 2.Record.
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
ADT Binary Search Tree Ellen Walker CPSC 201 Data Structures Hiram College.
Binary Search Trees (BST)
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
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.
Search: Binary Search Trees Dr. Yingwu Zhu. Review: Linear Search Collection of data items to be searched is organized in a list x 1, x 2, … x n – Assume.
1 the BSTree class  BSTreeNode has same structure as binary tree nodes  elements stored in a BSTree are a key- value pair  must be a class (or a struct)
Course: Programming II - Abstract Data Types HeapsSlide Number 1 The ADT Heap So far we have seen the following sorting types : 1) Linked List sort by.
1 Binary Search Trees. 2 Binary Search Trees Binary Search Trees The Binary Search Tree (BST) Search, Insertion and Traversal of BST Removal of nodes.
CSE373: Data Structures & Algorithms Priority Queues
Chapter 12 – Data Structures
Non Linear Data Structure
Data Structures and Design in Java © Rick Mercer
Trees Chapter 15.
Data Structure and Algorithms
COMP 53 – Week Fourteen Trees.
Trees Chapter 11 (continued)
Recursive Objects (Part 4)
Trees Chapter 11 (continued)
Binary Search Tree (BST)
Lecture 22 Binary Search Trees Chapter 10 of textbook
Week 11 - Friday CS221.
Hashing Exercises.
abstract containers sequence/linear (1 to 1) hierarchical (1 to many)
ITEC 2620M Introduction to Data Structures
Binary Trees, Binary Search Trees
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
Binary Search Trees.
Assignment 3 Biggest deductions No decomposition
What remains Topics Assignments Final exam
CMSC 341 Lecture 10 B-Trees Based on slides from Dr. Katherine Gibson.
original list {67, 33,49, 21, 25, 94} pass { } {67 94}
Searching: Binary Trees
Priority Queues and Heaps
Part-D1 Priority Queues
Ch. 8 Priority Queues And Heaps
CMSC 341 Binary Search Trees.
Lecture 12 CS203 1.
Binary Search Trees.
Binary Trees, Binary Search Trees
CMSC 341 Binary Search Trees.
CSC 143 Binary Search Trees.
EE 312 Final Exam Review.
Yan Shi CS/SE 2630 Lecture Notes
Trees.
CMSC 341 Binary Search Trees 2/21/2006.
Binary Trees, Binary Search Trees
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

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 element with this key return true; else return false Add(element) – if there is no element with this element’s key, add it to the map and return true; else return false Remove(key) – if there is an element with this key, remove it from the map and return true; else return false Retrieve(key) – if there is an element with this key, return the value; else return null

Many ways to store the elements of a map Linked list Vector Binary search tree Balanced search tree Hash table

Assignments 5 and 6 Both require implementing a map (as defined in mapinterface.h) Assignment 5 - using a linked list Assignment 6 - using a binary search tree You do not know what the map is going to be used for What will a program that wants to use your map class need to do in order to use it?

If you were writing a program that needed to use a priority queue could you use the priority queue class you wrote for Assignment 4?

The priority Queue interface Operation Description size() Return number of elements in the PQ isEmpty() Returns true if PQ is empty, else false enqueue(element) Add element to the PQ dequeue() Remove element with the highest priority front() Return element with the highest priority

Writing a c++ class that provides priority queue behavior (optional) define a Priorityqueueinterface abstract class Define the class in pq.h typedef statement for itemtype Public section Method Prototype with comment describing behavior for each operation in the interface Default constructor Big 3 methods as needed Nothing else! Private section Data members depending on how items are being stored Implement the class in pq.cpp

Divide and conquer

2 ways to apply divide and conquer strategy when writing a program Using classes that do pieces of what the program needs to do Container classes List, stack, queue, priority queue, map, graph Classes specific to the program Type of items – itemtoPurchase, call Shopping cart Call center Functional decomposition

Architecture of assignment 4 has-a program CallCenter has-a Priority Queue has-many Call

Which is better? main main int,double int, double getSysVar user simulate terminal int, double user simulate terminal

Binary search trees

binary search tree A binary search tree is a binary tree that has the bst property Each item holds a value Its left child is either empty or holds a smaller value Its right child is either empty or holds a larger value Are recursive 45 36 56 42 25 52 60 30 50

Storing the elements of a bst Have to store each element along with how that element is related to other elements Parent, left child, right child can we store the elements in a vector so we can calculate where an element’s parent, left child and right child are stored? Yes, but very inefficient for a binary search tree Linked storage stores each element in a node along with pointers to its children and (maybe) its parent Needs a pointer to the root (like head for a linked list)

45 36 56 25 42 52 60 30 50 root Each node holds a key-value pair, only the key is shown here

How do we find/retrieve an element? 45 36 56 25 42 52 60 30 50 root

How do we add an element? 45 36 56 25 42 52 60 30 50 root

An exercise Starting with an empty binary search tree Draw the BST that results from adding (in the order shown) elements with the following keys 52 23 67 12 36 98 25 73 30 Repeat with 6 8 7 12 25

52 23 67 12 36 98 25 73 30 6 8 7 12 25 52 / \ 23 67 / \ \ 12 36 98 / / 25 73 \ 30 6 \ 8 / \ 7 12 25

operations all start by searching for element with given key Find – follow path from root If found return true If not found return false Retrieve – follow path from root If found return value If not found return null add – follow path from root If found return false If not found add node at end of the path followed and return true remove – follow path from root If found delete that node (or another node) and return true

Searching a bst Search algorithm can be iterative or recursive Zybook shows iterative search algorithm Will look at recursive search algorithm in class A bst is recursively defined

Outline for A recursive search function bool search (nodePointer, key) if nodePointer is null // base case #1 else if element in this node has the key // base case #2 else if key < key of element in this node search left subtree else search right subtree

Implementing map methods recursively find, add, retrieve and remove methods do not have a node* as a parameter Find, add, remove, retrieve need to call recursive helper methods These will have a node* as a parameter Each recursive call will search a smaller BST What happens when a base case is reached is different for each method

Recursive helper methods Are called by map methods Need to be defined as private methods (in .h) Ex: Bool find(keytype key, node* p); Should the node* parameter be Pass by value? Pass by reference? Pass by const reference?

How do we remove an item? 45 36 56 25 42 52 60 30 50 root

Removing an element Start by searching for the element with the given key If element not found return false If element found Case 1: element is in a leaf node Change pointer from parent to null and delete node Case 2: element is in a node with one empty subtree Change pointer from parent to point to the non-empty subtree and delete node Case 3: element is in a node with no empty subtrees Find smallest item in the right subtree (or largest in the left subtree) Replace the element to be deleted with that element Delete the node containing that element It will have at least one empty subtree

45 36 56 25 42 52 60 30 50 root remove (50) remove (25) remove (45)

If you are storing the elements of a map in a linked list that is sorted based on the key values do you need to write a sort function or method?

Traversing a collection of items “visit” each item in the collection once visit is some action to be taken with each item There is more than one order in which the items can be visited In what orders can the items in a list be visited? First to last Last to first Some operations that require traversing a collection of items Displaying all items Making a copy of a linked list (or BST) Destructor for a linked list (or bst)

Traversing a bst Three common orders in which to visit the items in a Bst Preorder Visit the root Traverse the left subtree Traverse the right subtree Postorder Inorder

45 36 56 42 25 52 60 30 50 preorder: postorder: inorder:

45 36 56 42 25 52 60 30 50 preorder: 45 36 25 30 42 56 52 50 60 postorder: 30 25 42 36 50 52 60 56 45 inorder: 25 30 36 42 45 50 52 56 60

Backing up a bst Searching a bst follows a path of successors Do not need to go from a node to its parent Traversing a bst requires backing up the tree Go from a node to its parent 3 ways to do this Each node has a parent pointer Use recursion Keep a stack of node pointers that is used to back up the tree

Outline for a recursive traversal of a bst if BST is empty return // base case – no tree to traverse visit the root traverse the left subtree traverse the right subtree what parameter(s) are required? what kind of traversal is done? how to do other traversals?

Outline for a recursive traversal of a bst if BST is empty return // base case – no tree to traverse visit the root traverse the left subtree traverse the right subtree what parameter(s) are required? - Node* p what kind of traversal is done? - preorder how to do other traversals? - move “visit the root”

Some reasons to traverse a bst Display elements in the bst Traversal order? What does visit mean? Free all the nodes of a bst (destructor) Make a copy of a bst (copy constructor)

Some reasons to traverse a bst Display elements in the bst Traversal order -- inorder (most likely) What does visit mean -- insert element into an istream Free all the nodes of a bst (destructor) Traversal order -- postorder What does visit mean -- delete a node Make a copy of a bst (copy constructor) Traversal order -- preorder What does visit mean -- allocate a node and store an element in it

Some map data structures data structure add find remove retrieve array (unordered) O(n)* O(n) O(n) O(n) array (ordered by key) O(n) O(log2 n) O(n) O(log2 n) linked list (unordered) O(n) * O(n) O(n) O(n) linked list (ordered by key) O(n) O(n) O(n) O(n) binary search tree ?? ?? ?? ?? * key must be unique

Big o depends on length of search path followed Length of search paths depends on height of the tree Height of the tree depends on order in which items were added Suppose we added the items in order of their keys? Height of a bst containing n items Worst case: Best case: Average case:

Big o depends on length of search path followed Length of search paths depends on height of the tree Height of the tree depends on order in which items were added Suppose we added the items in order of their keys? Height of a bst containing n items Worst case: n-1 Best case: floor (log2 n) Average case: 1.5 (log2 n)

Why storing a bst in an array is too inefficient to be usble

A complete binary tree All levels except the bottom most have all possible nodes Nodes on the bottom most level fill the left most positions

A complete binary tree can be efficiently stored in an array 0 1 2 3 4 5 6 7 8 9 10 11 12 -----

Allows computation of location of an element’s parent, left child and right child left child of i is at 2 * i + 1 right child of i is at 2 * i + 2 parent of i is at (i – 1) / 2 How can we tell if there is no left or right child? How can we tell if there is no parent? 0 1 2 3 4 5 6 7 8 9 10 11 12 -----

Requires memory space for all possible items Level number possible number of items total possible number of items in a at this level binary tree with this many levels Level 0 1 1 Level 1 2 3 Level 2 4 7 Level 3 8 15 Level 4 16 31 Level n 2n 2n+1 -1

What size array is needed? What size array is needed? 52 / \ 23 67 / \ \ 12 36 98 / / 25 73 \ 30 6 \ 8 / \ 7 12 25

What size array is needed? What size array is needed? 52 / \ 23 67 / \ \ 12 36 98 / / 25 73 \ 30 6 \ 8 / \ 7 12 25 15 to hold 5 actual elements 31 to hold 9 actual items

Zybook assignment before Tuesday’s class do ch.20 – hash tables

Exam 2 Thursday March 29 Memory management Hierarchical collections Run-time stack Heap Big 3 methods (destructor, copy constructor, operator=) Hierarchical collections General Trees Priority queue adt implementations Recursion Set and map adts Binary search tree