Programming Abstractions Cynthia Lee CS106X. Topics:  Binary Search Tree (BST) › Starting with a dream: binary search in a linked list? › How our dream.

Slides:



Advertisements
Similar presentations
CS 332: Algorithms Binary Search Trees. Review: Dynamic Sets ● Next few lectures will focus on data structures rather than straight algorithms ● In particular,
Advertisements

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.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary trees Reading: L&C 9.1 – 9.7.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
BST Data Structure A BST node contains: A BST contains
Data Structures Data Structures Topic #8. Today’s Agenda Continue Discussing Table Abstractions But, this time, let’s talk about them in terms of new.
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
1 Red-Black Trees. 2 Black-Height of the tree = 4.
© 2006 Pearson Addison-Wesley. All rights reserved11 A-1 Chapter 11 Trees.
Fall 2007CS 2251 Self-Balancing Search Trees Chapter 9.
Chapter 12 Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define trees as data structures Define the terms.
Trees Chapter 23 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Fundamentals of Python: From First Programs Through Data Structures
Deletion algorithm – Phase 2: Remove node or replace its with successor TreeNode deleteNode(TreeNode n) { // Returns a reference to a node which replaced.
1 Joe Meehean.  Important and common problem  Given a collection, determine whether value v is a member  Common variation given a collection of unique.
C o n f i d e n t i a l HOME NEXT Subject Name: Data Structure Using C Unit Title: Trees.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Trees.
Priority Queues and Heaps Bryce Boe 2013/11/20 CS24, Fall 2013.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
CS 2133: Data Structures Binary Search Trees.
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
Advanced Algorithms Analysis and Design Lecture 8 (Continue Lecture 7…..) Elementry Data Structures By Engr Huma Ayub Vine.
PRIORITY QUEUES (HEAPS). Queues are a standard mechanism for ordering tasks on a first-come, first-served basis However, some tasks may be more important.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templatized Tree.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary search trees.
CS 3610 Midterm Review.
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
Tree (new ADT) Terminology:  A tree is a collection of elements (nodes)  Each node may have 0 or more successors (called children)  How many does a.
CS106X – Programming Abstractions in C++ Cynthia Bailey Lee CS2 in C++ Peer Instruction Materials by Cynthia Bailey Lee is licensed under a Creative Commons.
B-Trees and Red Black Trees. Binary Trees B Trees spread data all over – Fine for memory – Bad on disks.
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.
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.
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.
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.
Red–black trees.  Define the red-black tree properties  Describe and implement rotations  Implement red-black tree insertion  We will skip red-black.
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 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.
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.
Programming Abstractions Cynthia Lee CS106X. Topics:  Finish up heap data structure implementation › Enqueue (“bubble up”) › Dequeue (“trickle down”)
+ David Kauchak cs312 Review. + Midterm Will be posted online this afternoon You will have 2 hours to take it watch your time! if you get stuck on a problem,
Week 7 - Friday.  What did we talk about last time?  Trees in general  Binary search trees.
Binary Search Trees Data Structures Ananda Gunawardena
1 Chapter 7 Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation of the binary search tree.
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.
Trees Chapter 23 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
Binary Search Trees (BST)
Rooted Tree a b d ef i j g h c k root parent node (self) child descendent leaf (no children) e, i, k, g, h are leaves internal node (not a leaf) sibling.
Binary Search Trees … From
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
Binary Search Trees.  Understand tree terminology  Understand and implement tree traversals  Define the binary search tree property  Implement binary.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
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.
CMSC 202, Version 5/02 1 Trees. CMSC 202, Version 5/02 2 Tree Basics 1.A tree is a set of nodes. 2.A tree may be empty (i.e., contain no nodes). 3.If.
Dictionaries CS 110: Data Structures and Algorithms First Semester,
CS6045: Advanced Algorithms Data Structures. Dynamic Sets Next few lectures will focus on data structures rather than straight algorithms In particular,
DS.T.1 Trees Chapter 4 Overview Tree Concepts Traversals Binary Trees Binary Search Trees AVL Trees Splay Trees B-Trees.
Trees Chapter 15.
Programming Abstractions
Programming Abstractions
Week 6 - Wednesday CS221.
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.
Tree Rotations and AVL Trees
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Presentation transcript:

Programming Abstractions Cynthia Lee CS106X

Topics:  Binary Search Tree (BST) › Starting with a dream: binary search in a linked list? › How our dream provided the inspiration for the BST Note: we do NOT actually construct BSTs using this method › BST insert › Big-O analysis of BST › BST balance issues  Traversals › Pre-order › In-order › Post-order › Breadth-first  Applications of Traversals 2

An Idealized Binary Search Tree Important note of clarification: When I was talking about setting up the tree as a binary search (pic at left), that was an explanation of the inspiration for BST. Lining up the values and then arranging the pointers all at once is not how we use them (insert one at a time using algorithm we talked about).

What is the worst case cost for doing containsKey() in BST if the BST is balanced? O(logN)—awesome! BSTs is that they are great when balanced BST is bad when unbalanced Balance depends on order of insert of elements

Ok, so, long-chain BSTs are bad, should we worry about it? [math puzzle time] One way to create a bad BST is to insert the elements in decreasing order: 34, 22, 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 the 4 nodes listed above? A.2-3 B.4-5 C.6-7 D.8-9 E.More than 9 Bonus question: general formula for any BST of size n? Extra bonus question (CS109): what is this as a fraction of all trees (i.e., probability of worst-case tree).

BST Balance Strategies So we definitely need to balance, how can we do that if the tree location is fixed when we insert?

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 Unportedhttp://commons.wikimedia.org/wiki/File:Red-black_tree_example.svg Video:

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 B-Tree

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. Most commonly-searched items move to the top, saving time › For search terms, imagine “Bieber” would be near the root, and “polymorphism” would be further down by the leaves, because humanity is disappointing sometimes… B-Tree  Like BST, but a node can have many children, not just 2  Used for huge databases

BST and Heap quick recap/cheat sheet

13 BST and Heap quick recap/cheat sheet Heap (Priority Queue)  Structure: must be “complete”  Order: parent priority must be <= both children › This is for min-heap, opposite is true for max-heap › No rule about whether left child is > or < the right child  Big-O: guaranteed log(n) enqueue and dequeue  Operations: always add to end of array and then “bubble up”; for dequeue do “trickle down” BST (Map)  Structure: any valid binary tree  Order: leftchild.key < self.key < rightchild.key › No duplicate keys › Because it’s a Map, values go along for the ride w/keys  Big-O: log(n) if balanced, but might not be balanced, then linear  Operations: recursively repeat: start at root and go left if key root

Tree Traversals! These are not only for Binary Search Trees, but we often do them on BSTs

What does this print? (assume we call traverse on the root node to start) void traverse(Node *node) { if (node != NULL) { cout key << " "; traverse(node->left); traverse(node->right); } A. A B C D E F B. A B D E C F C. D B E F C A D. D E B F C A E. Other/none/more A BC DEF

What does this print? (assume we call traverse on the root node to start) void traverse(Node *node) { if (node != NULL) { traverse(node->left); traverse(node->right); cout key << " "; } A. A B C D E F B. A B D E C F C. D B E F C A D. D E B F C A E. Other/none/more A BC DEF

What does this print? (assume we call traverse on the root node to start) void traverse(Node *node) { if (node != NULL) { traverse(node->left); cout key << " "; traverse(node->right); } A B C D E. Other/none/more

How can we get code to print our ABCs in order as shown? (note: not BST order) void traverse(Node *node) { if (node != NULL) { ?? cout key << " "; traverse(node->left); traverse(node->right); } You can’t do it by using this code and moving around the cout—we already tried moving the cout to all 3 possible places and it didn’t print in order  You can but you use a queue instead of recursion  “Breadth-first” search  Again we see this key theme A BC DEF

Applications of Tree Traversals Beautiful little things from an algorithms/theory standpoint, but they have a practical side too!

Traversals a very commonly-used tool in your CS toolkit void traverse(Node *node) { if (node != NULL) { traverse(node->left); // “do something” traverse(node->right); }  Customize and move the “do something,” and that’s the basis for dozens of algorithms and applications

Map interface implemented with BST  Remember how when you iterate over the Stanford library Map you get the keys in sorted order? › (we used this for the word occurrence counting code example in class) void printMap(const Map & themap) { for (string s : themap) { cout << s; // printed in sorted order }  Now you know why it can do that in O(N) time! › “In-order” traversal

Applications of the traversals  You have a tree that represents evaluation of an arithmetic expression. Which traversal would form the foundation of your evaluation algorithm? A. Pre-order B. In-order C. Post-order D. Breadth-first * +/ 3428

Applications of the traversals  You are writing the destructor for a BST class. Given a pointer to the root, it needs to free each node. Which traversal would form the foundation of your destructor algorithm? A. Pre-order B. In-order C. Post-order D. Breadth-first BST