CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.

Slides:



Advertisements
Similar presentations
CS 261 – Data Structures AVL Trees. Binary Search Tree: Balance Complexity of BST operations: proportional to the length of the path from the root to.
Advertisements

1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
CSE 12 – Basic Data Structures Cynthia Bailey Lee Some slides and figures adapted from Paul Kube’s CSE 12 CS2 in Java Peer Instruction Materials by Cynthia.
AA Trees another alternative to AVL trees. Balanced Binary Search Trees A Binary Search Tree (BST) of N nodes is balanced if height is in O(log N) A balanced.
EECS 311: Chapter 4 Notes Chris Riesbeck EECS Northwestern.
InOrder Traversal Algorithm // InOrder traversal algorithm inOrder(TreeNode n) { if (n != null) { inOrder(n.getLeft()); visit(n) inOrder(n.getRight());
CS 307 Fundamentals of Computer Science 1 Abstract Data Types many slides taken from Mike Scott, UT Austin.
1 Balanced Search Trees  several varieties  AVL trees  trees  Red-Black trees  B-Trees (used for searching secondary memory)  nodes are added.
Balanced Search Trees (Ch. 13) To implement a symbol table, Binary Search Trees work pretty well, except… The worst case is O(n) and it is embarassingly.
Trees and Red-Black Trees Gordon College Prof. Brinton.
CS 206 Introduction to Computer Science II 11 / 24 / 2008 Instructor: Michael Eckmann.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Ch. 13: Balanced Search Trees Symbol table: insert, delete, find, pred, succ, sort,… Binary Search Tree review: What is a BST? binary tree with a key at.
Deletion algorithm – Phase 2: Remove node or replace its with successor TreeNode deleteNode(TreeNode n) { // Returns a reference to a node which replaced.
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.
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
Binary Search Trees. BST Properties Have all properties of binary tree Items in left subtree are smaller than items in any node Items in right subtree.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
1 Hash Tables  a hash table is an array of size Tsize  has index positions 0.. Tsize-1  two types of hash tables  open hash table  array element type.
Dictionaries CS 105. L11: Dictionaries Slide 2 Definition The Dictionary Data Structure structure that facilitates searching objects are stored with search.
CS 106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
Chapter 3 List Stacks and Queues. Data Structures Data structure is a representation of data and the operations allowed on that data. Data structure is.
Balanced Search Trees Chapter 27 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
CS 106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
Course: Programming II - Abstract Data Types Red-Black TreesSlide Number 1 Balanced Search Trees Binary Search Tree data structures can allow insertion,
Balancing Binary Search Trees. Balanced Binary Search Trees A BST is perfectly balanced if, for every node, the difference between the number of nodes.
Chapter 13 B Advanced Implementations of Tables – Balanced BSTs.
B-Trees and Red Black Trees. Binary Trees B Trees spread data all over – Fine for memory – Bad on disks.
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
Even MORE Balanced Trees Computing 2 COMP s1.
Red–black trees.  Define the red-black tree properties  Describe and implement rotations  Implement red-black tree insertion  We will skip red-black.
CSE 12 – Basic Data Structures Cynthia Bailey Lee Some slides and figures adapted from Paul Kube’s CSE 12 CS2 in Java Peer Instruction Materials by Cynthia.
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
CS 106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
CS 206 Introduction to Computer Science II 04 / 22 / 2009 Instructor: Michael Eckmann.
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
CSE 12 – Basic Data Structures Cynthia Bailey Lee Some slides and figures adapted from Paul Kube’s CSE 12 CS2 in Java Peer Instruction Materials by Cynthia.
Week 8 - Wednesday.  What did we talk about last time?  Level order traversal  BST delete  2-3 trees.
Week 8 - Monday.  What did we talk about last time?  BST traversals  Get range implementation.
Dictionaries CS /02/05 L7: Dictionaries Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
Programming Abstractions Cynthia Lee CS106X. Topics:  Finish up heap data structure implementation › Enqueue (“bubble up”) › Dequeue (“trickle down”)
Programming Abstractions Cynthia Lee CS106X. Topics:  Binary Search Tree (BST) › Starting with a dream: binary search in a linked list? › How our dream.
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.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 15 Other Data Structures Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
CS 261 – Recitation 7 Spring 2015 Oregon State University School of Electrical Engineering and Computer Science.
FALL 2005CENG 213 Data Structures1 Priority Queues (Heaps) Reference: Chapter 7.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
Dictionaries CS 110: Data Structures and Algorithms First Semester,
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)
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
Programming Abstractions
Week 7 - Friday CS221.
BST Trees
Programming Abstractions
Programming Abstractions
Tree data structure.
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.
original list {67, 33,49, 21, 25, 94} pass { } {67 94}
Wednesday, April 18, 2018 Announcements… For Today…
Tree data structure.
Programming Abstractions
CS 106B Lecture 20: Binary Search Trees Wednesday, May 17, 2017
CS 261 – Data Structures AVL Trees.
Presentation transcript:

CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License. Permissions beyond the scope of this license may be available at Bailey LeeCreative Commons Attribution-NonCommercial- ShareAlike 4.0 International Licensehttp://peerinstruction4cs.org

Today’s Topics: BSTs! 1. Binary Search in a linked list? 2. Template interfaces and the TreeMap 3. Binary Search Tree 2

Implementing Map interface with a Binary Search Tree (BST)  Usually we think of a hash table as the go-to implementation of the Map interface  We will study hash tables on Monday!  Binary Search Trees are another option  C++’s Standard Template Library (STL) uses a Red-Black tree (type of BST) for their map  Stanford library also uses a BST

Binary Search in a Linked List? Exploring a good idea, finding way to make it work

Imagine storing sorted data in an array  How long does it take us to find? Binary search!

Can we do binary search on a linked list to implement a quick insert? A. It’s a great idea as long as you have a doubly-linked list B. Even with a doubly-linked list the performance is not good, because linked list nodes are strewn all over the heap so you can’t jump right to a middle one C. It’s a great idea as long as you make sure that your linked list nodes follow one another in heap memory with no gaps so you can jump to the middle one D. Other/none/more

Imagine storing sorted data in an array  How long does it take us to find? Binary search!  But when we insert into an array, even if we have some extra space at the end, we have to move everything over—O(n) to do the insert after O(log n) to find where to insert  Linked list has dynamic structure that has O(1) to do insert after O(n) to find where to insert

Adjusting our Linked List to support array-style binary search

TreeMap An implementation of the Map interface that has guaranteed log(n) worst case.

tree-map.h template class TreeMap { public: TreeMap(); ~TreeMap(); bool isEmpty() const { return size() == 0; } int size() const { return count; } bool containsKey(const Key& key) const; void put(const Key& key, const Value& value); Value get(const Key& key) const; Value& operator[](const Key& key);...

tree-map.h... private: struct node { Key key; Value value; node *left, *right; }; int count; node *root; void disposeTree(node *root); const node * const & findNode(const Key& key) const; node *ensureNodeExists(const Key& key); }; #include "tree-map-impl.h"

BST put()  Insert: 22, 9, 34, 18, 3  How many of these result in the same tree structure as above?  22, 34, 9, 18, 3  22, 18, 9, 3, 34  22, 9, 3, 18, 34 A. None of these B. 1 of these C. 2 of these D. All of these

tree-map.h template void TreeMap ::put(const Key& key, const Value& value) { node ** currp = &root; while (*currp != NULL && !((*currp)->key == key)) { if ((*currp)->key right; else currp = &(*currp)->left; } if (*currp == NULL) { *currp = new node(key, value, NULL, NULL); } else (*currp)->value = value; }

Bad BSTs  One way to create a bad BST is to insert the elements in order: 34, 22, 18, 9, 3  That’s not the only way…  How many distinctly structured BSTs are there that exhibit the worst case height (height equals number of nodes) for a tree with 5 nodes? A. 2-3 B. 4-5 C. 6-7 D. 8-9 E. More than 9

What is the BEST CASE cost for doing containsKey() in BST? A. O(1) B. O(log n) C. O(n) D. O(n log n) E. O(n 2 )

What is the WORST CASE cost for doing containsKey() in BST? A. O(1) B. O(log n) C. O(n) D. O(n log n) E. O(n 2 )

What is the WORST CASE cost for doing containsKey() in BST if the BST is complete ? A. O(1) B. O(log n) C. O(n) D. O(n log n) E. O(n 2 )

BALANCE!!!  The #1 issue to remember with BSTs is that they are great when balanced (O(log n) operations), and horrible when unbalanced (O(n) operations)  Balance depends on order of insert of elements  Over the years, people have devised many ways of making sure BSTs stay balanced no matter what order the elements are inserted

BST Balance Strategies

Red-Black trees  One of the most famous (and most tricky) strategies for keeping a BST balanced  Not guaranteed to be perfectly balanced, but “close enough” to keep O(log n) guarantee on operations

Red-Black trees  In addition to the requirements imposed on a binary search trees, red–black trees must meet these:  A node is either red or black.  The root is black.  All leaves (null children) are black.  Both children of every red node are black.  Every simple path from a given node to any of its descendant leaves contains the same number of black nodes.  (This is what guarantees “close” to balance)

Red-Black trees  Every simple path from a given node to any of its descendant leaves contains the same number of black nodes.  (This is what guarantees “close” to balance) This file is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported license. CommonsAttribution-Share Alike 3.0 Unported

Insert procedure must maintain the invariants (this gets tricky)  Video: This file is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported license. CommonsAttribution-Share Alike 3.0 Unported

Other BST balance strategies  Red-Black tree  AVL tree  Treap (BST + heap in one tree! What could be cooler than that, amirite? ♥ ♥ ♥ ) Other fun types of BST :  Splay tree  Rather than only worrying about balance, Splay Tree dynamically readjusts based on how often users search for an item. Commonly-searched items move to the top, saving time  B-Tree  Like BST, but a node can have many children, not just 2