CSE100. Advanced Data Structures. Lecture 4. (Based on Paul Kube course materials)

Similar documents
CSE 100: C++ TEMPLATES AND ITERATORS

CSE 100: C++ TEMPLATES AND ITERATORS

CSE 100: C++ TEMPLATES AND ITERATORS

TEMPLATES AND ITERATORS

Chapter 20: Binary Trees

Chapter 5. The Standard Template Library.

Structuur van Computerprogramma s 2

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

Trees. Chapter 6. strings. 3 Both position and Enumerator are similar in concept to C++ iterators, although the details are quite different.

CSE100. Advanced Data Structures. Lecture 13. (Based on Paul Kube course materials)

(8 1) Container Classes & Class Templates D & D Chapter 18. Instructor - Andrew S. O Fallon CptS 122 (October 8, 2018) Washington State University

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

CSCI-1200 Data Structures Spring 2015 Lecture 20 Trees, Part III

CSCI-1200 Data Structures Fall 2018 Lecture 19 Trees, Part III

CMSC 341 Lecture 10 Binary Search Trees

Improving the Return Value of Erase-Like Algorithms

Dynamic Data Structures

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms

Traversing Trees with Iterators

Traversing Trees with Iterators

CSCI-1200 Data Structures Fall 2014 Lecture 18 Trees, Part III

B-Trees. nodes with many children a type node a class for B-trees. an elaborate example the insertion algorithm removing elements

CSE100. Advanced Data Structures. Lecture 12. (Based on Paul Kube course materials)

void insert( Type const & ) void push_front( Type const & )

COEN244: Class & function templates

Tree Travsersals and BST Iterators

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Lecture 2. Binary Trees & Implementations. Yusuf Pisan

SETS AND MAPS. Chapter 9

We have the pointers reference the next node in an inorder traversal; called threads

list<t>::const_iterator it1 = lst.begin(); // points to first element list<t>::const_iterator it2 = lst.begin(); // points to second element it2++;

CSCI-1200 Data Structures Spring 2018 Lecture 18 Trees, Part III

List, Stack, and Queues

Computational Physics

PIC10B/1 Winter 2014 Final Exam Study Guide

LECTURE 11 TREE TRAVERSALS

Priority Queues and Huffman Trees

Binary Search Trees Part Two

Chapter 17. Linked Data Structures. Copyright 2016 Pearson, Inc. All rights reserved.

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.

Suppose that the following is from a correct C++ program:

CSCI-1200 Data Structures Fall 2016 Lecture 17 Associative Containers (Maps), Part 2

STL: C++ Standard Library

CS11 Advanced C++ Fall Lecture 1

CSC212 Data Structure - Section FG

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013

Introduction to C++ Introduction to C++ 1

CMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC

Binary Search Trees Treesort

CS197c: Programming in C++

TDDD38 - Advanced programming in C++

An Introduction to Trees

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013

CSCI-1200 Data Structures Spring 2018 Lecture 15 Associative Containers (Maps), Part 2

STL Containers, Part II

CSCI-1200 Data Structures Test 3 Practice Problem Solutions

Binary Search Trees. Contents. Steven J. Zeil. July 11, Definition: Binary Search Trees The Binary Search Tree ADT...

CSCI-1200 Data Structures Spring 2016 Lecture 22 Priority Queues, part II (& Functors)

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

Dictionaries. Priority Queues

STL Standard Template Library

Lists. linking nodes. constructors. chasing pointers. MCS 360 Lecture 11 Introduction to Data Structures Jan Verschelde, 17 September 2010.

Introduction to C++ Systems Programming

CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism

7 TEMPLATES AND STL. 7.1 Function Templates

CSCI-1200 Data Structures Spring 2018 Lecture 16 Trees, Part I

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)

CSCI-1200 Data Structures Fall 2018 Lecture 23 Priority Queues II

Module 4: Index Structures Lecture 13: Index structure. The Lecture Contains: Index structure. Binary search tree (BST) B-tree. B+-tree.

CSCI-1200 Data Structures Spring 2015 Lecture 18 Trees, Part I

CSE100 Practice Final Exam Section C Fall 2015: Dec 10 th, Problem Topic Points Possible Points Earned Grader

CSCI-1200 Data Structures Fall 2017 Lecture 18 Trees, Part II

CS102 Binary Search Trees

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

Figure 1. A breadth-first traversal.

CSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too)

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures

LECTURE 18 AVL TREES

Sets and MultiSets. Contents. Steven J. Zeil. July 19, Overview of Sets and Maps 4

Unit 4 Basic Collections

Problem Set 1. You might want to read Chapter 12 of the course reader before attempting this problem.

Lecture No.07. // print the final avaerage wait time.

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

Binary Trees and Binary Search Trees

CS 104 (Spring 2014) Final Exam 05/09/2014

Function Templates. Consider the following function:

UNIVERSITY OF MASSACHUSETTS LOWELL Department of Electrical and Computer Engineering. Program 8 EECE.3220 Data Structures Fall 2017

a graph is a data structure made up of nodes in graph theory the links are normally called edges

CSCI-1200 Data Structures Fall 2017 Lecture 17 Trees, Part I

CSI33 Data Structures

C++ 11 and the Standard Library: Containers, Iterators, Algorithms

use static size for this buffer

Outline. Variables Automatic type inference. Generic programming. Generic programming. Templates Template compilation

CSCI-1200 Data Structures Fall 2017 Test 3 Solutions

Section 1: True / False (2 points each, 30 pts total)

CSCI 104 Binary Trees / Priority Queues / Heaps. Mark Redekopp Michael Crowley

CPSC 427a: Object-Oriented Programming

Transcription:

CSE100 Advanced Data Structures Lecture 4 (Based on Paul Kube course materials)

Lecture 4 Binary search trees Toward a binary search tree implementation using C++ templates Reading: Weiss Ch 4, sections 1-4

Binary search trees A binary search tree is a data structure with these invariants: Structural property: a BST is a binary tree Ordering property: Each node in a BST has a data item, sometimes called a key, associated with it Keys in a BST belong to an ordered set, which means that...... for any two keys k 1, k 2 exactly one of these is true: k 1 is less than k 2 ; k 2 is less than k 1 ; k 1 and k 2 are equal Then, for every node X in a BST: the key in X is greater than every key in X s left subtree the key in X is less than every key in X s right subtree (so, a BST does not hold duplicate keys)

Binary search tree examples Which of these are BSTs, and which are not?

Implementing binary search trees In an implementation of a BST, nodes should be designed to hold: a pointer to the left child of the node (null if no left child) a pointer to the right child of the node (null if no right child) a pointer to, or reference to, or copy of, the data item associated with the node For some algorithms, it is convenient if the nodes also have: a pointer to the parent (null if this node is the root) a field to hold additional implementation-specific information about the node (balance number, color, priority...)

A Node class template for BST nodes Simple C++ Node class template for BST nodes and generic keys: template <typename T> class Node { public: }; T key; Node<T>* left; Node<T>* right; Node<T>* parent; int info;

The basic Find operation in a binary search tree Idea: exploit the ordering property of BST s; each key comparison either finds the key you are looking for, or tells you which subtree (left or right) to look in next; if that subtree is empty, the key is not in the tree. Note: it is a C++ STL convention to use only < for key comparisons Pseudocode for the basic iterative algorithm to Find key with value k in a BST: 1. If RootNode == nullptr, tree is empty (no root). Return false. 2. Set CurrNode = RootNode. 3. If k < CurrNode.key... /* key must be in left subtree, if it is in the tree. */ If CurrNode.left == nullptr, return false. else set CurrNode = CurrNode.left, and go to 3. 4. else If CurrNode.key < k... /* key must be in right subtree, if it is in the tree. */ If CurrNode.right == nullptr, return false. else set CurrNode = CurrNode.right, and go to 3. 5. else Found the key; it is in CurrNode. Return true.

The Insert operation in a binary search tree Again, the idea is to make use of the ordering property of BST s; each key comparison tells you which subtree the key must go in, so the find algorithm can find it later But (unlike finds) inserts modify the tree. It is important to maintain all the BST invariants: If you start with a BST, the result after insertion must still be a BST! Pseudocode for the basic iterative algorithm to Insert key with value k in a BST: 1. If RootNode == nullptr, tree is empty. Set RootNode = new Node(k). Done. 2. Set CurrNode = RootNode. 3. If k < CurrNode.key... /* key must go in left subtree */ If CurrNode.left == nullptr, set CurrNode.left = new Node(k). Done. else set CurrNode = CurrNode.left, and go to 3. 4. else If CurrNode.key < k... /* key must go in right subtree */ If CurrNode.right == nullptr, set CurrNode.right = new Node(k). Done. else set CurrNode = CurrNode.right, and go to 3. 5. else Found the key; Done. /* A BST typically does not contain duplicates */

C++ STL and binary search trees The C++ Standard Template Library provides these containers (i.e., data structures): array vector deque forward_list list stack queue priority_queue set multiset unordered_set map unordered_map multimap bitset Of these, set and map are implemented using a balanced binary search tree (typically a red-black tree) Let s look at some aspects of the interface of set and consider issues in implementing it

C++ STL set find member function set s find function has this prototype: template <typename T> class set { public: iterator find ( T const & x ) const; Note: find takes an argument that is a reference to a const T the actual argument is not copied (it would be copied if the & was left out) x is a direct reference to the actual argument, not a pointer to it but the T that x is a reference to must be treated as const by find: it cannot change it Note: find is a const member function it is an accessor only it cannot change anything about the set whose find function is being called

C++ STL set find function semantics The documentation for set::find says: Searches the container for an element with a value of x and returns an iterator to it if found, otherwise it returns an iterator to the element past the end of the container. Searching a binary search tree for an element with the value of x is easy, as long as you can compare x and data items stored in nodes of the tree (using <)... just use the standard BST find algorithm But then the function is supposed to return an iterator (to the node where x is found, or past the end of the container if not) We will need to study C++ iterators to see how to do that

C++ STL set insert function set s insert function has this prototype: template <typename T> class set { public: std::pair<iterator,bool> insert ( T const & x ); Note: insert takes an argument that is a reference to a const T the actual argument is not copied (it would be copied if the & was left out) x is a direct reference to the actual argument, not a pointer to it but the T that x is a reference to must be treated as const by find: it cannot change it Note: insert is a mutator; it is not a const member function Note: insert returns a pair containing an iterator and a bool

C++ STL set insert function semantics The documentation for set::insert says: The set container is extended by inserting a single new element. This effectively increases the container size by the amount of elements inserted. Because set containers do not allow for duplicate values, the insertion operation checks for each element inserted whether another element exists already in the container with the same value, if so, the element is not inserted and an iterator to it is returned. The function returns a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the element that already had its same value in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an element with the same value existed. Inserting a value x in a BST is easy, as long as you can compare x (using < ) to data items stored in nodes of the tree... just use the standard BST insert algorithm Again, the function is supposed to return an iterator, as an element of a std::pair

std::pair Definition of the pair struct template: template <class T1, class T2> struct pair { T1 first; T2 second; pair(const T1& x, const T2& y) : first(x), second(y) {} }; (Note: in C++, a struct is exactly the same as a class, except that members are public by default; in a class, members are private by default) Example of using pair, and of using the function template make_pair: #include <utility> #include <string> #include <iostream> int main () { std::pair <std::string,double> pr ("tomatoes",3.25); std::cout << pr.first << ", " << pr.second << std::endl; pr.second = 4.50; std::cout << pr.first << ", " << pr.second << std::endl; pr = make_pair("oranges",2.75); std::cout << pr.first << ", " << pr.second << std::endl;

C++ STL iterators In the iterator pattern of OO design, a container has a way to supply to a client an iterator object which is to be used by the client to access the data in the container sequentially, without exposing the container s underlying representation Containers in the STL implement the iterator pattern For example here s a typical way client code can iterate over (and print out) all of the data in an STL container, in this case a set: set<string> c;... // get an iterator pointing to container s first element set<string>::iterator itr = c.begin(); // get an iterator pointing past container s last element set<string>::iterator end = c.end(); // loop while itr is not past the last element while(itr!= end) { cout << *itr << endl; // dereference the itr to get data ++itr; // increment itr to point to next element }

Next time C++ iterators The binary search tree successor function Reading: Weiss Ch 4, sections 1-4