Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees

Similar documents
Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees

Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees

Self-Balancing Search Trees. Chapter 11

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

CIS265/ Trees Red-Black Trees. Some of the following material is from:

Sorted Arrays. Operation Access Search Selection Predecessor Successor Output (print) Insert Delete Extract-Min

2-3 Tree. Outline B-TREE. catch(...){ printf( "Assignment::SolveProblem() AAAA!"); } ADD SLIDES ON DISJOINT SETS

Binary Trees, Binary Search Trees

CS350: Data Structures B-Trees

Binary Search Trees. Analysis of Algorithms

CS102 Binary Search Trees

Overview of Presentation. Heapsort. Heap Properties. What is Heap? Building a Heap. Two Basic Procedure on Heap

Define the red- black tree properties Describe and implement rotations Implement red- black tree insertion

Lecture 13: AVL Trees and Binary Heaps

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

CS 350 : Data Structures B-Trees

Data Structures and Algorithms

Hash Tables. CS 311 Data Structures and Algorithms Lecture Slides. Wednesday, April 22, Glenn G. Chappell

Analysis of Algorithms

CS350: Data Structures Red-Black Trees

Binary Trees. BSTs. For example: Jargon: Data Structures & Algorithms. root node. level: internal node. edge.

ECE 242 Data Structures and Algorithms. Heaps I. Lecture 22. Prof. Eric Polizzi

Binary Tree. Preview. Binary Tree. Binary Tree. Binary Search Tree 10/2/2017. Binary Tree

Chapter 6 Heaps. Introduction. Heap Model. Heap Implementation

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

BINARY SEARCH TREES cs2420 Introduction to Algorithms and Data Structures Spring 2015

Dictionaries. Priority Queues

DATA STRUCTURES AND ALGORITHMS. Hierarchical data structures: AVL tree, Bayer tree, Heap

Heapsort. Why study Heapsort?

Priority Queues and Heaps. Heaps of fun, for everyone!

ECE 242 Data Structures and Algorithms. Trees IV. Lecture 21. Prof.

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

Trees, Part 1: Unbalanced Trees

CMPS 2200 Fall 2017 Red-black trees Carola Wenk

CMSC 341 Lecture 14: Priority Queues, Heaps

Binary search trees (chapters )

Garbage Collection: recycling unused memory

Trees. (Trees) Data Structures and Programming Spring / 28

Algorithms. Deleting from Red-Black Trees B-Trees

CS 206 Introduction to Computer Science II

Multi-way Search Trees! M-Way Search! M-Way Search Trees Representation!

Design and Analysis of Algorithms - Chapter 6 6

Fall, 2015 Prof. Jungkeun Park

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

Binary heaps (chapters ) Leftist heaps

Section 4 SOLUTION: AVL Trees & B-Trees

Red-Black Trees. Based on materials by Dennis Frey, Yun Peng, Jian Chen, and Daniel Hood

Motivation Computer Information Systems Storage Retrieval Updates. Binary Search Trees. OrderedStructures. Binary Search Tree

CSE 502 Class 16. Jeremy Buhler Steve Cole. March A while back, we introduced the idea of collections to put hash tables in context.

Algorithms in Systems Engineering ISE 172. Lecture 16. Dr. Ted Ralphs

Binary Trees and Binary Search Trees

Binary Search Trees Treesort

Algorithms. AVL Tree

TREES. Trees - Introduction

Data Structures and Algorithms for Engineers

Spring 2018 Mentoring 8: March 14, Binary Trees

Tables, Priority Queues, Heaps

Transform & Conquer. Presorting

CMSC 341 Priority Queues & Heaps. Based on slides from previous iterations of this course

Heap Model. specialized queue required heap (priority queue) provides at least

CSE 373 OCTOBER 11 TH TRAVERSALS AND AVL

Advanced Set Representation Methods

CSI33 Data Structures

Binary search trees (chapters )

CS 240 Fall Mike Lam, Professor. Priority Queues and Heaps

Priority Queues Heaps Heapsort

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

CMSC 341 Lecture 10 Binary Search Trees

CSCI Trees. Mark Redekopp David Kempe

Cpt S 122 Data Structures. Data Structures Trees

Search Trees - 2. Venkatanatha Sarma Y. Lecture delivered by: Assistant Professor MSRSAS-Bangalore. M.S Ramaiah School of Advanced Studies - Bangalore

A set of nodes (or vertices) with a single starting point

B-Trees. Version of October 2, B-Trees Version of October 2, / 22

8. Binary Search Tree

BRONX COMMUNITY COLLEGE of the City University of New York DEPARTMENT OF MATHEMATICS AND COMPUTER SCIENCE

COMP171. AVL-Trees (Part 1)

CMSC 341 Leftist Heaps

Trees. Eric McCreath

CH 8. HEAPS AND PRIORITY QUEUES

Programming II (CS300)

Uses for Trees About Trees Binary Trees. Trees. Seth Long. January 31, 2010

CH. 8 PRIORITY QUEUES AND HEAPS

B-Trees. Based on materials by D. Frey and T. Anastasio

Computer Science 210 Data Structures Siena College Fall Topic Notes: Priority Queues and Heaps

CMPT 225. Red black trees

CS 315 Data Structures mid-term 2

Lecture 6: Analysis of Algorithms (CS )

Data Structures and Algorithms

AVL Trees Heaps And Complexity

Data Structures. Outline. Introduction Linked Lists Stacks Queues Trees Deitel & Associates, Inc. All rights reserved.

Binary Search Tree (3A) Young Won Lim 6/2/18

9. Heap : Priority Queue

Multi-way Search Trees. (Multi-way Search Trees) Data Structures and Programming Spring / 25

UNIT III BALANCED SEARCH TREES AND INDEXING

Binary Search Trees > = 2014 Goodrich, Tamassia, Goldwasser. Binary Search Trees 1

Operations on Heap Tree The major operations required to be performed on a heap tree are Insertion, Deletion, and Merging.

3. Priority Queues. ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority.

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

Balanced Binary Search Trees. Victor Gao

Balanced Search Trees

Transcription:

Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees

Linked representation of binary tree Again, as with linked list, entire tree can be represented with a single pointer -- in this case, a pointer to the root node Nodes are instances of class BTnode, described in the next several slides The class contains methods that operate on single nodes Since each node is potentially the root node of a tree (or subtree), we will also include operations on entire trees

Linked representation of binary tree

Methods of BTnode class

Methods of BTnode class

Static methods operate at tree level Accessors (entire tree): treesize() returns number of nodes in tree treecopy() returns a new tree copied from a source tree argument

Output methods

Constructor

Simple accessor methods

Recursive accessors

Mutators

Mutators

Static methods public static <E> BTNode<E> treecopy(btnode<e> source) { BTNode<E> leftcopy, rightcopy; if (source == null) return null; else { leftcopy = treecopy(source.left); rightcopy = treecopy(source.right); return new BTNode<E>(source.data, leftcopy, rightcopy); } }

Static methods

Tree traversal

Now, more ways to climb!

Example: printing all nodes // pre-order traversal public void preorderprint( ) { System.out.println(data); if (left!= null) left.preorderprint( ); if (right!= null) right.preorderprint( ); }

Example: printing all nodes

Example: printing all nodes (part 1)

Example: printing all nodes (part 2)

Example: printing all nodes (part 3)

A forest full of trees The generic BTNode class we have seen thus far can be used to create many types of data structures derived from binary trees Now we will look at a specific ADT based on the generic binary tree: binary search trees

BST characteristics Based on binary trees Defining quality has to do with the order in which data are stored Commonly used in database applications where rapid retrieval of data is desired

Binary Search Trees Entries in a BST must be objects to which total order semantics apply -- in other words, objects for which all the binary comparison operations are defined Storage rules -- for every node n: every entry in n s left subtree is less than or equal to the entry in n every entry in n s right subtree is greater than n s entry

Unlike a heap, a BST has no special requirement for the tree to maintain a particular shape but a balanced tree (in which there are approximately the same number of nodes in each subtree) facilitates data searching Binary Search Tree

The Dictionary Data Type A dictionary is a collection of items, similar to a bag. Unlike a bag, each item is ordered according to an intrinsic or extrinsic value called the item's key. We have seen how a hash table might be used to implement the Dictionary ADT; now we'll implement it as binary search tree

A Dictionary of States in BST Form Storage rules: Every key to the left of a node is alphabetically before the key of the node. Every key to the right of a node is alphabetically after the key of the node.

Start at the root. If the current node has the key, then stop and retrieve the data. If the current node's key is too large, move left and repeat previous steps If the current node's key is too small, move right and repeat previous steps Retrieving Data

Adding Pretend that you are trying to find the key, but stop when there is no node to move to. Add the new node at the spot where you would have moved to if there had been a node.

Where would you add the 51 st state? Adding

Removing an Item with a Given Key Find the item. If necessary, swap the item with one that is easier to remove. Remove the item.

Removing an Item with a Given Key Find the item. If the node is not a leaf: If the node has 1 child, replace the parent with the child If the item has 2 children, rearrange the tree: Find smallest item in the right subtree Copy that smallest item onto the one that you want to remove Remove the extra copy of the smallest item (making sure that you keep the tree connected) Else just remove the item.

Summary Binary search trees are a good implementation of data types such as sets, bags, and dictionaries. Searching for an item is generally quick since you move from the root to the item, without looking at many other items. Adding and deleting items is also quick. But it is possible for the quickness to fail in some cases -- can you see why?

The problem of balance In the best case, the average execution time for the following operations on a binary search tree: Search Insertion Deletion is a respectable O(log N). The average actual time (mathematically beyond the scope of this course) is about twice that still very good (and better than any sorting algorithm we ve seen, including HeapSort) But worst case is O(N) this is what we get if values are inserted in order

The problem of balance Binary search trees are usually balanced only if insertion occurs in random order: Perfectly balanced Unbalanced (entries were added in reverse order) More typical fairly balanced

Red-black trees: a variation on the BST Goal: keep the tree balanced by: Adding an extra data field to each node represented as a color, either red or black (but really just a boolean value) Imposing a set of rules related to node color (see next slide) Graphic source: Wikipedia

Red-Black Tree Rules Every node is either red or black Null nodes (links from leaves) are always black Red nodes have 2 black children (note that this means that leaf nodes can be either red or black) If a node is red, its parent is black Every path from any node to its lowest leaf s null link(s) contains the same number of black nodes (not counting the origin node)

Enforcing the rules: rotation Operation on a parent node and one of its children Left rotation: parent node swaps positions with its right child Right rotation: parent node swaps positions with its left child May involve color changes May propogate up the tree

Rotation Source: Wikipedia

Recoloring Thank you Wikipedia!

Red-Black Tree Live! https://www.cs.usfca.edu/~galles/visualization/redblack.html