CMSC 341 Leftist Heaps

Similar documents
CMSC 341 Lecture 15 Leftist Heaps

CMSC 341 Lecture 15 Leftist Heaps

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

CMSC 341 Lecture 14: Priority Queues, Heaps

CMSC 341. Binary Heaps. Priority Queues

Arrays aren t going to work. What can we do? Use pointers Copy a large section of a heap, with a single pointer assignment

Chapter 6 Heaps. Introduction. Heap Model. Heap Implementation

CMSC 341 Lecture 10 Binary Search Trees

Data Structures and Algorithms

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

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

CSE 5311 Notes 4a: Priority Queues

Binary heaps (chapters ) Leftist heaps

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

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

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

Priority Queues and Binary Heaps

CS350: Data Structures Heaps and Priority Queues

COMP : Trees. COMP20012 Trees 219

Trees. A tree is a directed graph with the property

CSCI2100B Data Structures Heaps

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

CS102 Binary Search Trees

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

CSCI 136 Data Structures & Advanced Programming. Lecture 22 Fall 2018 Instructor: Bills

Data Structures and Algorithms

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

Advanced Algorithms. Class Notes for Thursday, September 18, 2014 Bernard Moret

INF2220: algorithms and data structures Series 4

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

Thus, it is reasonable to compare binary search trees and binary heaps as is shown in Table 1.

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

SKEW HEAPS: Self-Adjusting Heaps

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

CSCI Trees. Mark Redekopp David Kempe

CE 221 Data Structures and Algorithms

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof.

Sorting and Searching

CMSC 341. Binary Search Trees CMSC 341 BST

Implementations. Priority Queues. Heaps and Heap Order. The Insert Operation CS206 CS206

Binary Trees, Binary Search Trees

Chapter 5. Binary Trees

Binary Heaps in Dynamic Arrays

Sorting and Searching

4. Trees. 4.1 Preliminaries. 4.2 Binary trees. 4.3 Binary search trees. 4.4 AVL trees. 4.5 Splay trees. 4.6 B-trees. 4. Trees

Priority Queues. Lecture15: Heaps. Priority Queue ADT. Sequence based Priority Queue

Topic: Heaps and priority queues

Data Structures Week #8. Heaps (Priority Queues)

Binary Heaps. CSE 373 Data Structures Lecture 11

Leftist Heaps and Skew Heaps. (Leftist Heaps and Skew Heaps) Data Structures and Programming Spring / 41

CSE 214 Computer Science II Heaps and Priority Queues

Recall: Properties of B-Trees

Lecture Notes for Advanced Algorithms

Dictionaries. Priority Queues

Section 1: True / False (1 point each, 15 pts total)

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

I2206 Data Structures TS 6: Binary Trees - Binary Search Trees

Figure 1: A complete binary tree.

Binary Heaps. COL 106 Shweta Agrawal and Amit Kumar

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

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

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

Heap: A binary heap is a complete binary tree in which each, node other than root is smaller than its parent. Heap example: Fig 1. NPTEL IIT Guwahati

Binary Trees. Recursive definition. Is this a binary tree?

CSI33 Data Structures

Chapter 20: Binary Trees

Advanced Set Representation Methods

CompSci 201 Tree Traversals & Heaps

The priority is indicated by a number, the lower the number - the higher the priority.

Maintain binary search tree property nodes to the left are less than the current node, nodes to the right are greater

An AVL tree with N nodes is an excellent data. The Big-Oh analysis shows that most operations finish within O(log N) time

CS 234. Module 8. November 15, CS 234 Module 8 ADT Priority Queue 1 / 22

Data Structures Lesson 9

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

Priority queues. Priority queues. Priority queue operations

Heaps. 2/13/2006 Heaps 1

The heap is essentially an array-based binary tree with either the biggest or smallest element at the root.

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

Heaps with merging. We can implement the other priority queue operations in terms of merging!

Priority Queues Heaps Heapsort

Readings. Priority Queue ADT. FindMin Problem. Priority Queues & Binary Heaps. List implementation of a Priority Queue

Algorithms and Data Structures

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

Binary Trees

Data Structures and Algorithms

Announcements. Midterm exam 2, Thursday, May 18. Today s topic: Binary trees (Ch. 8) Next topic: Priority queues and heaps. Break around 11:45am

Trees, Part 1: Unbalanced Trees

Algorithms. Deleting from Red-Black Trees B-Trees

Priority Queues. Binary Heaps

CS21003 Algorithms I, Autumn

Properties of a heap (represented by an array A)

Priority Queues, Binary Heaps, and Heapsort

Test #2. Login: 2 PROBLEM 1 : (Balance (6points)) Insert the following elements into an AVL tree. Make sure you show the tree before and after each ro

Describe how to implement deque ADT using two stacks as the only instance variables. What are the running times of the methods

(2,4) Trees. 2/22/2006 (2,4) Trees 1

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

Trees, Binary Trees, and Binary Search Trees

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

Priority Queues. e.g. jobs sent to a printer, Operating system job scheduler in a multi-user environment. Simulation environments

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

Transcription:

CMSC 341 Leftist Heaps Based on slides from previous iterations of this course

Today s Topics Review of Min Heaps Introduction of Left-ist Heaps Merge Operation Heap Operations

Review of Heaps

Min Binary Heap A min binary heap is a Complete binary tree Neither child is smaller than the value in the parent Both children are at least as large as the parent In other words, smaller items go above larger ones

Min Binary Heap Performance Performance (n is the number of elements in the heap) construction O( n ) findmin() O( 1 ) insert() O( lg n ) deletemin() O( lg n )

Introduction to Leftist Heaps

Leftist Heap Concepts Structurally, a leftist heap is a min tree where each node is marked with a rank value. Uses a Binary Tree (BT)!! Merging heaps is much easier and faster May use already established links to merge with a new node Rather than copying pieces of an array

Leftist Heap Concepts Values STILL obey a heap order (partial order) Uses a null path length to maintain the structure (covered in detail later) The null path of a node s left child is >= null path of the right child At every node, the shortest path to a non-full node is along the rightmost path!!!

Leftist Heap Example A leftist heap, then, is a purposefully unbalanced binary tree (leaning to the left, hence the name) that keeps its smallest value at the top and has an inexpensive merge operation 2 4 3 6 8 5 6 8 9

Leftist Heap Performance Leftist Heaps support: findmin() = O(1) deletemin() = O(log n) insert() = O(log n) construct = O(n) merge() = O(log n)

Null Path Length (npl) Length of shortest path from current node (X) to a node without 2 children value is stored IN the node itself leafs npl = 0 nodes with only 1 child npl = 0

Null Path Length (npl) Calculation 2 4 3 To calculate the npl for each node, we look to see how many nodes we need to traverse to get to an open node 6 8 5 6 8 9

Null Path Length (npl) Calculation 2 4 3 In the leaves case, there is a null position 0 nodes away 6 8 5 6 8 0 / 0 9 0 / 0 0 / 0 0 / 0

Null Path Length (npl) Calculation In these cases, one side is 0 and the other side is 1 2 4 3 0 / 1 6 8 5 6 8 0 / 1 9

Null Path Length (npl) Calculation 2 / 1 2 / 1 2 4 3 In the root, it will take two levels to get to null to the left; one to the right. 1 / 1 6 8 5 6 8 9

Leftist Node The node for a leftist heap will have many member variables this time links (left and right) element (data) npl By default, the Leftist Heap sets an empty node as the root

Leftist Node Code private: struct LeftistNode { Comparable element; LeftistNode *left; LeftistNode *right; int npl; Looks like a binary tree node except the npl being stored. }; LeftistNode( const Comparable & theelement, LeftistNode *lt = NULL, LeftistNode *rt = NULL, int np = 0 ) : element( theelement ), left( lt ), right( rt ), npl( np ) { } LeftistNode *root;

Building a Leftist Heap

Building a Leftist Heap Value of node STILL matters Lowest value will be root, so still a min Heap Data entered is random Uses CURRENT npl of a node to determine where the next node will be placed

Moves in Building Leftist Heap 50 New leftist heap with one node

Moves in Building Leftist Heap 50 Normal insertion of a new node into the tree value 75. 75 First placed as far right as possible. Then swung left to satisfy npls.

Moves in Building Leftist Heap 25 50 Normal insertion of a new node into the tree value 25. 75 As this is a min Tree, 25 is the new root. Then swung left to satisfy npls.

Moves in Building Leftist Heap 50 25 55 Normal insertion of a new node into the tree value 55. 75 No swing required.

Moves in Building Leftist Heap 75 25 50 55 40 What is wrong with this? Normal insertion of a new node into the tree value 40. Not a min heap at this point. Need to swap 40 and 55 and swing.

Moves in Building Leftist Heap 50 25 40 Normal insertion of a new node into the tree value 40. 75 55 Not a min heap at this point. Need to swap 40 and 55 and swing.

Moves in Building Leftist Heap 1/2 50 25 40 Normal insertion of a new node into the tree value 65. 75 55 65 While this is still a min heap, the npl at the root is not leftist

Moves in Building Leftist Heap 2/1 40 25 50 We need change this from 1/2 to 2/1 so that it remains leftist. 55 65 75 To do this, we switch the left and the right subtrees. After we do the swap, the npl of the root is compliant.

Leftist Heap Algorithm Add new node to right-side of tree, in order If new node is to be inserted as a parent (parent < children) make new node parent link children to it link grandparent down to new node (now new parent) If leaf, attach to right of parent If no left sibling, push to left (hence left-ist) why?? (answer in a second) Else left node is present, leave at right child Update all ancestors npls Check each time that all nodes left npl > = right npls if not, swap children or node where this condition exists

Building a Leftist Heap Example 21, 14, 17, 10, 3, 23, 26, 8 21

Building a Leftist Heap Example 21, 14, 17, 10, 3, 23, 26, 8 21 14 Insert 14 as the new root

Building a Leftist Heap Example 21, 14, 17, 10, 3, 23, 26, 8 14 21 17 Insert 17 as the right child of 14

Building a Leftist Heap Example 14 21 17 10 21, 14, 17, 10, 3, 23, 26, 8 Insert 10 as the new root

Building a Leftist Heap Example 14 21 17 10 3 21, 14, 17, 10, 3, 23, 26, 8 Insert 3 as the new root

Building a Leftist Heap Example 10 3 23 21, 14, 17, 10, 3, 23, 26, 8 14 21 17 Insert 23 as the right child of 3

Building a Leftist Heap Example 10 3 23 21, 14, 17, 10, 3, 23, 26, 8 14 21 17 26 Insert 26 as the right child of 23 Swing 26 to the left

Building a Leftist Heap Example 10 3 8 21, 14, 17, 10, 3, 23, 26, 8 14 21 17 26 23 Take the right subtree of root 3: nodes 23 & 26 Insert 8 as the new root (parent of 23) Reattach to original root

Merging Leftist Heaps

Merging Leftist Heaps In the code, adding a single node is treated as merging a heap (just one node) with an established heap s root And work from that root as we just went over We will go over merging whole heaps momentarily But in reality, isn t ONE node a heap??

Merging Leftist Heaps The heaps we are about to merge must be LEFTIST heaps At the end we will get a heap that is both a min-heap leftist

Merging Leftist Heaps The Merge procedure takes two leftist trees, A and B, and returns a leftist tree that contains the union of the elements of A and B. In a program, a leftist tree is represented by a pointer to its root.

Merging Leftist Heaps Example 10 1 0 5 15 0 1 0 50 2 1 7 20 25 0 99 1 0 0 75 0 22 Where should we attempt to merge?

Merging Leftist Heaps Example 7 20 25 75 22 50 99 In the right sub-tree

Merging Leftist Heaps Example 22 25 75 All the way down to the right most node

Merging Leftist Heaps Example 22 75 25 As there are two nodes in the right subtree, swap. Important: We don t split a heap, so 22 must be the parent in this merge

Merging Leftist Heaps Example 22 75 25 Merge two subtrees

Merging Leftist Heaps Example 7 20 22 50 99 75 25 Next level of the tree

Merging Leftist Heaps Example 1 5 1 7 2 10 15 20 22 50 99 75 25 Right side of the tree has a npl of 2 so we need to swap

Merging Leftist Heaps Example 7 2 2 1 1 5 20 22 10 15 50 99 75 25 Now the highest npl is on the left.

Merging Leftist Heaps Start at the (sub) root, and finalize the node AND LEFT with the smallest value REPEADLY, until no lists left unmerged. Start at the rightmost root of the sub-tree, and finalize the node AND LEFT with the next smallest value in leftist lists. Add to RIGHT of finalized tree. Verify that it is a Min Heap!! (Parent < Children) Verify a leftist heap! (left npl >= right npl) if not, swap troubled node with sibling

Merging Leftist Heaps Code /** * Merge rhs into the priority queue. * rhs becomes empty. rhs must be different from this. */ void merge( LeftistHeap & rhs ) { if( this == &rhs ) // Avoid aliasing problems return; } root = merge( root, rhs.root ); rhs.root = NULL;

Merging Leftist Heaps Code /** * Internal method to merge two roots. * Deals with deviant cases and calls recursive merge1. */ LeftistNode * merge( LeftistNode *h1, LeftistNode *h2 ) { if( h1 == NULL ) return h2; if( h2 == NULL ) return h1; if( h1->element < h2->element ) return merge1( h1, h2 ); else return merge1( h2, h1 ); }

Merging Leftist Heaps Code /** * Internal method to merge two roots. * Assumes trees are not empty, & h1's root contains smallest item. */ LeftistNode * merge1( LeftistNode *h1, LeftistNode *h2 ) { if( h1->left == NULL ) // Single node h1->left = h2; // Other fields in h1 already accurate else { h1->right = merge( h1->right, h2 ); if( h1->left->npl < h1->right->npl ) swapchildren( h1 ); h1->npl = h1->right->npl + 1; } return h1; }

Deleting from Leftist Heap

Deleting from Leftist Heap Simple to just remove a node (since at top) this will make two trees Merge the two trees like we just did

Deleting from Leftist Heap 1 3 8 0 0 0 14 23 2 10 21 17 0 26 1 0 We remove the root.

Deleting from Leftist Heap 1 3 8 0 0 0 14 23 2 10 21 17 0 26 1 0 Then we do a merge and because min is in left subtree, we recursively merge right into left

Deleting from Leftist Heap 1 3 8 0 0 0 14 23 2 10 21 17 0 26 1 0 Then we do a merge and because min is in left subtree, we recursively merge right into left

Deleting from Leftist Heap 0 21 23 1 8 1 0 10 14 1 0 17 26 0 After Merge

Leftist Heaps Merge with two trees of size n O(log n), we are not creating a totally new tree!! some was used as the LEFT side! Inserting into a left-ist heap O(log n) same as before with a regular heap deletemin with heap size n O(log n) remove and return root (minimum value) merge left and right subtrees

Announcements Project 3 Due Tuesday, November 7th at 8:59:59 PM