SlideShare a Scribd company logo
Introduction
A leftist heap or leftist tree is a priority queue. It is implemented with a variant of
the binary heap. We store the distance of the nearest leaf in the subtree rooted at a
node for every node. Let us call this value s-value. Leftist heap attempts to be very
unbalanced which is in contrast to a binary heap, which is always a complete binary
tree.
Also see, Implementation of Heap
A leftist heap is an implementation of a mergeable heap. While inserting a new node
into the heap, a new one-node heap is created, which is merged into the existing
heap. To delete an item, we replace it with the merge of its left and right subtrees.
Leftist heaps are useful because of their ability to merge quickly (in O(logN) time)
compared to binary heaps that take O(N) time.
Time Complexities
The following are the time complexities of various operations of a leftist heap:
Function Complexity
Get Min O(1)
Delete Min O(logN)
Insert O(logN)
Merge O(logN)
Properties
 The following are the properties of a leftist heap:
1. Key(i) >= Key(parent(i)): This is similar to normal min-heap property.
2. The right descendant of every node has a smaller s-value. This means that the
number of edges on the shortest path from a node to a leaf of the right child is
less than or equal to that of the left child.
 From the above properties, we can conclude the following:
1. The smallest path from any leaf to the root is the path from the root to the
rightmost leaf.
2. If there are ‘X’ nodes in the path from the root to the rightmost leaf, then the
leftist heap will have at least (2x
- 1) nodes.
3. From point 2, we can also conclude that the length of the path from the root to
the leftmost leaf is O(logN) for a leftist heap having N nodes.
Operations
1. merge(): The main operation of a leftist heap is the merge operation.
2. deleteMin(): This can be done by replacing the minimum node with the merge of
left and right subtrees.
3. insert(): This can be done by calling the merge function on the original heap and
a new one-node heap.
S-value or Dist
The s-value (or dist) of a node is the distance between that node and the nearest
leaf in the subtree of that node. The dist of a null child is 0 (In some implementations,
the dist of a null child is assumed to be -1).
Merging
Since the right subtree of a leftist heap is smaller than the left subtree, we merge the
right subtree with the other tree.
The following are the steps for merge operation:
1. Make the root with a smaller value than the new root.
2. Push this root into an empty stack and move to its right child.
3. Recursively compare the two keys, keep pushing the smaller key into the stack,
and move to its right child.
4. Perform step 3 until a null node is reached.
5. Pick the last node processed and make it the right child of the node present at
the top of the stack.
6. Recursively pop the elements from the stack and keep making them the right
child of the new node present at the stack top.
Merging visualization
Inserting into a leftist heap
The insertion operation is done using the merge operation. We create a new leftist
heap with a single node having a value of the element to be inserted. We then merge
this newly created heap with the existing heap.
1. newHeap = createLeftistHeap(val)
2. merge(leftistHeap, newHeap)
Deleting Min element from a leftist heap
The min-element is the root of a leftist heap. So, to delete the min-element, we
replace the root element with the merge of its left and right subtrees.
1. Val = root.val
2. root = merge(root.right, root.left)
3. Return val
Implementation
// C++ program for leftist heap / leftist tree
#include <bits/stdc++.h>
using namespace std;
// Defining class Node for leftist heap node.
class Node
{
public:
int val;
Node *left;
Node *right;
int dist;
Node(int &val, Node *lt = NULL, Node *rt = NULL, int np = 0)
{
this->val = val;
right = rt;
left = lt,
dist = np;
}
};
// Defining Leftist Heap functions.
class LeftistHeap
{
public:
LeftistHeap();
LeftistHeap(LeftistHeap &rhs);
~LeftistHeap();
bool isEmpty();
bool isFull();
int &findMin();
void Insert(int &x);
void deleteMin();
void deleteMin(int &minItem);
void makeEmpty();
void Merge(LeftistHeap &rhs);
LeftistHeap &operator=(LeftistHeap &rhs);
private:
Node *root;
Node *Merge(Node *h1,
Node *h2);
Node *Merge1(Node *h1,
Node *h2);
void swapChildren(Node *t);
void reclaimMemory(Node *t);
Node *clone(Node *t);
};
// Function to construct leftist heap
LeftistHeap::LeftistHeap()
{
root = NULL;
}
// Copy constructor.
LeftistHeap::LeftistHeap(LeftistHeap &rhs)
{
root = NULL;
*this = rhs;
}
// Destructor for the leftist heap
LeftistHeap::~LeftistHeap()
{
makeEmpty();
}
// Function to merge rhs into the priority queue.
void LeftistHeap::Merge(LeftistHeap &rhs)
{
if (this == &rhs)
return;
root = Merge(root, rhs.root);
rhs.root = NULL;
}
// Function to merge two roots
Node *LeftistHeap::Merge(Node *h1,
Node *h2)
{
if (h1 == NULL)
return h2;
if (h2 == NULL)
return h1;
if (h1->val < h2->val)
return Merge1(h1, h2);
else
return Merge1(h2, h1);
}
// Function to merge two roots.
Node *LeftistHeap::Merge1(Node *h1,
Node *h2)
{
if (h1->left == NULL)
h1->left = h2;
else
{
h1->right = Merge(h1->right, h2);
if (h1->left->dist < h1->right->dist)
swapChildren(h1);
h1->dist = h1->right->dist + 1;
}
return h1;
}
// Function to swap children of a node.
void LeftistHeap::swapChildren(Node *t)
{
Node *tmp = t->left;
t->left = t->right;
t->right = tmp;
}
// Function to insert an item into leftist heap
void LeftistHeap::Insert(int &x)
{
root = Merge(new Node(x), root);
}
// Function to find the smallest item.
int &LeftistHeap::findMin()
{
return root->val;
}
// Function to remove the smallest item.
void LeftistHeap::deleteMin()
{
Node *oldRoot = root;
root = Merge(root->left, root->right);
delete oldRoot;
}
// Function to remove the smallest item.
void LeftistHeap::deleteMin(int &minItem)
{
if (isEmpty())
{
cout << "Heap is Empty" << endl;
return;
}
minItem = findMin();
deleteMin();
}
// Function to test if the priority queue is logically empty.
bool LeftistHeap::isEmpty()
{
return root == NULL;
}
// Function to test if the priority queue is logically full.
bool LeftistHeap::isFull()
{
return false;
}
// Make the priority queue logically empty
void LeftistHeap::makeEmpty()
{
reclaimMemory(root);
root = NULL;
}
// Deep copy
LeftistHeap &LeftistHeap::operator=(LeftistHeap &rhs)
{
if (this != &rhs)
{
makeEmpty();
root = clone(rhs.root);
}
return *this;
}
// Internal method to make the tree empty.
void LeftistHeap::reclaimMemory(Node *t)
{
if (t != NULL){
reclaimMemory(t->left);
reclaimMemory(t->right);
delete t;
}
}
// Internal method to clone subtree.
Node *LeftistHeap::clone(Node *t)
{
if (t == NULL){
return NULL;
}
else{
return new Node(t->val, clone(t->left), clone(t->right), t->dist);
}
}
// Driver program
int main()
{
LeftistHeap h;
LeftistHeap h1;
LeftistHeap h2;
int x;
int arr[] = {1, 5, 7, 10, 15};
int arr1[] = {22, 75};
h.Insert(arr[0]);
h.Insert(arr[1]);
h.Insert(arr[2]);
h.Insert(arr[3]);
h.Insert(arr[4]);
h1.Insert(arr1[0]);
h1.Insert(arr1[1]);
h.deleteMin(x);
cout << x << endl;
h1.deleteMin(x);
cout << x << endl;
h.Merge(h1);
h2 = h;
h2.deleteMin(x);
cout << x << endl;
return 0;
}
Output
1
22
5

More Related Content

Similar to Leftlist Heap-1.pdf

Heaps
HeapsHeaps
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic ProgammingAlgorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Traian Rebedea
 
3.7 heap sort
3.7 heap sort3.7 heap sort
3.7 heap sort
Krish_ver2
 
Advanced s and s algorithm.ppt
Advanced s and s algorithm.pptAdvanced s and s algorithm.ppt
Advanced s and s algorithm.ppt
LegesseSamuel
 
03-data-structures.pdf
03-data-structures.pdf03-data-structures.pdf
03-data-structures.pdf
Nash229987
 
C++ ProgramRecursive reversal of a tree.[16] Write a method voi.pdf
C++ ProgramRecursive reversal of a tree.[16] Write a method voi.pdfC++ ProgramRecursive reversal of a tree.[16] Write a method voi.pdf
C++ ProgramRecursive reversal of a tree.[16] Write a method voi.pdf
funkybabyindia
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structuresNiraj Agarwal
 
Once you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docxOnce you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docx
farrahkur54
 
(a) There are three ways to traverse a binary tree pre-order, in-or.docx
(a) There are three ways to traverse a binary tree pre-order, in-or.docx(a) There are three ways to traverse a binary tree pre-order, in-or.docx
(a) There are three ways to traverse a binary tree pre-order, in-or.docx
ajoy21
 
Data Structure Lecture 7
Data Structure Lecture 7Data Structure Lecture 7
Data Structure Lecture 7Teksify
 
Sienna6bst 120411102353-phpapp02
Sienna6bst 120411102353-phpapp02Sienna6bst 120411102353-phpapp02
Sienna6bst 120411102353-phpapp02Getachew Ganfur
 
Heap Hand note
Heap Hand noteHeap Hand note
Heap Hand note
Abdur Rouf
 
Quick and Heap Sort with examples
Quick and Heap Sort with examplesQuick and Heap Sort with examples
Quick and Heap Sort with examples
Bst Ali
 
Data structures and algorithms lab10
Data structures and algorithms lab10Data structures and algorithms lab10
Data structures and algorithms lab10Bianca Teşilă
 
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docxAssg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
festockton
 
Lecture 5_ Sorting and order statistics.pptx
Lecture 5_ Sorting and order statistics.pptxLecture 5_ Sorting and order statistics.pptx
Lecture 5_ Sorting and order statistics.pptx
JosephKariuki46
 
computer notes - Stack
computer notes - Stackcomputer notes - Stack
computer notes - Stackecomputernotes
 

Similar to Leftlist Heap-1.pdf (20)

Heaps
HeapsHeaps
Heaps
 
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic ProgammingAlgorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
 
3.7 heap sort
3.7 heap sort3.7 heap sort
3.7 heap sort
 
Advanced s and s algorithm.ppt
Advanced s and s algorithm.pptAdvanced s and s algorithm.ppt
Advanced s and s algorithm.ppt
 
03-data-structures.pdf
03-data-structures.pdf03-data-structures.pdf
03-data-structures.pdf
 
C++ ProgramRecursive reversal of a tree.[16] Write a method voi.pdf
C++ ProgramRecursive reversal of a tree.[16] Write a method voi.pdfC++ ProgramRecursive reversal of a tree.[16] Write a method voi.pdf
C++ ProgramRecursive reversal of a tree.[16] Write a method voi.pdf
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structures
 
Once you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docxOnce you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docx
 
(a) There are three ways to traverse a binary tree pre-order, in-or.docx
(a) There are three ways to traverse a binary tree pre-order, in-or.docx(a) There are three ways to traverse a binary tree pre-order, in-or.docx
(a) There are three ways to traverse a binary tree pre-order, in-or.docx
 
Data Structure Lecture 7
Data Structure Lecture 7Data Structure Lecture 7
Data Structure Lecture 7
 
Sienna6bst 120411102353-phpapp02
Sienna6bst 120411102353-phpapp02Sienna6bst 120411102353-phpapp02
Sienna6bst 120411102353-phpapp02
 
Heap
HeapHeap
Heap
 
Heap Hand note
Heap Hand noteHeap Hand note
Heap Hand note
 
Quick and Heap Sort with examples
Quick and Heap Sort with examplesQuick and Heap Sort with examples
Quick and Heap Sort with examples
 
Data structures and algorithms lab10
Data structures and algorithms lab10Data structures and algorithms lab10
Data structures and algorithms lab10
 
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docxAssg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
 
Soft Heaps
Soft HeapsSoft Heaps
Soft Heaps
 
Lecture 5_ Sorting and order statistics.pptx
Lecture 5_ Sorting and order statistics.pptxLecture 5_ Sorting and order statistics.pptx
Lecture 5_ Sorting and order statistics.pptx
 
computer notes - Stack
computer notes - Stackcomputer notes - Stack
computer notes - Stack
 
Heaps & priority queues
Heaps & priority queuesHeaps & priority queues
Heaps & priority queues
 

Recently uploaded

The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 

Recently uploaded (20)

The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 

Leftlist Heap-1.pdf

  • 1. Introduction A leftist heap or leftist tree is a priority queue. It is implemented with a variant of the binary heap. We store the distance of the nearest leaf in the subtree rooted at a node for every node. Let us call this value s-value. Leftist heap attempts to be very unbalanced which is in contrast to a binary heap, which is always a complete binary tree. Also see, Implementation of Heap A leftist heap is an implementation of a mergeable heap. While inserting a new node into the heap, a new one-node heap is created, which is merged into the existing heap. To delete an item, we replace it with the merge of its left and right subtrees. Leftist heaps are useful because of their ability to merge quickly (in O(logN) time) compared to binary heaps that take O(N) time. Time Complexities The following are the time complexities of various operations of a leftist heap: Function Complexity Get Min O(1) Delete Min O(logN) Insert O(logN) Merge O(logN) Properties  The following are the properties of a leftist heap: 1. Key(i) >= Key(parent(i)): This is similar to normal min-heap property. 2. The right descendant of every node has a smaller s-value. This means that the number of edges on the shortest path from a node to a leaf of the right child is less than or equal to that of the left child.  From the above properties, we can conclude the following: 1. The smallest path from any leaf to the root is the path from the root to the rightmost leaf. 2. If there are ‘X’ nodes in the path from the root to the rightmost leaf, then the leftist heap will have at least (2x - 1) nodes. 3. From point 2, we can also conclude that the length of the path from the root to the leftmost leaf is O(logN) for a leftist heap having N nodes. Operations 1. merge(): The main operation of a leftist heap is the merge operation. 2. deleteMin(): This can be done by replacing the minimum node with the merge of left and right subtrees. 3. insert(): This can be done by calling the merge function on the original heap and a new one-node heap. S-value or Dist The s-value (or dist) of a node is the distance between that node and the nearest leaf in the subtree of that node. The dist of a null child is 0 (In some implementations, the dist of a null child is assumed to be -1).
  • 2. Merging Since the right subtree of a leftist heap is smaller than the left subtree, we merge the right subtree with the other tree. The following are the steps for merge operation: 1. Make the root with a smaller value than the new root. 2. Push this root into an empty stack and move to its right child. 3. Recursively compare the two keys, keep pushing the smaller key into the stack, and move to its right child. 4. Perform step 3 until a null node is reached. 5. Pick the last node processed and make it the right child of the node present at the top of the stack. 6. Recursively pop the elements from the stack and keep making them the right child of the new node present at the stack top. Merging visualization Inserting into a leftist heap The insertion operation is done using the merge operation. We create a new leftist heap with a single node having a value of the element to be inserted. We then merge this newly created heap with the existing heap. 1. newHeap = createLeftistHeap(val) 2. merge(leftistHeap, newHeap) Deleting Min element from a leftist heap The min-element is the root of a leftist heap. So, to delete the min-element, we replace the root element with the merge of its left and right subtrees. 1. Val = root.val 2. root = merge(root.right, root.left) 3. Return val
  • 3. Implementation // C++ program for leftist heap / leftist tree #include <bits/stdc++.h> using namespace std; // Defining class Node for leftist heap node. class Node { public: int val; Node *left; Node *right; int dist; Node(int &val, Node *lt = NULL, Node *rt = NULL, int np = 0) { this->val = val; right = rt; left = lt, dist = np; } }; // Defining Leftist Heap functions. class LeftistHeap { public: LeftistHeap(); LeftistHeap(LeftistHeap &rhs); ~LeftistHeap(); bool isEmpty(); bool isFull(); int &findMin(); void Insert(int &x); void deleteMin(); void deleteMin(int &minItem); void makeEmpty(); void Merge(LeftistHeap &rhs); LeftistHeap &operator=(LeftistHeap &rhs); private: Node *root; Node *Merge(Node *h1, Node *h2); Node *Merge1(Node *h1, Node *h2); void swapChildren(Node *t); void reclaimMemory(Node *t); Node *clone(Node *t); };
  • 4. // Function to construct leftist heap LeftistHeap::LeftistHeap() { root = NULL; } // Copy constructor. LeftistHeap::LeftistHeap(LeftistHeap &rhs) { root = NULL; *this = rhs; } // Destructor for the leftist heap LeftistHeap::~LeftistHeap() { makeEmpty(); } // Function to merge rhs into the priority queue. void LeftistHeap::Merge(LeftistHeap &rhs) { if (this == &rhs) return; root = Merge(root, rhs.root); rhs.root = NULL; } // Function to merge two roots Node *LeftistHeap::Merge(Node *h1, Node *h2) { if (h1 == NULL) return h2; if (h2 == NULL) return h1; if (h1->val < h2->val) return Merge1(h1, h2); else return Merge1(h2, h1); } // Function to merge two roots. Node *LeftistHeap::Merge1(Node *h1, Node *h2) { if (h1->left == NULL) h1->left = h2; else {
  • 5. h1->right = Merge(h1->right, h2); if (h1->left->dist < h1->right->dist) swapChildren(h1); h1->dist = h1->right->dist + 1; } return h1; } // Function to swap children of a node. void LeftistHeap::swapChildren(Node *t) { Node *tmp = t->left; t->left = t->right; t->right = tmp; } // Function to insert an item into leftist heap void LeftistHeap::Insert(int &x) { root = Merge(new Node(x), root); } // Function to find the smallest item. int &LeftistHeap::findMin() { return root->val; } // Function to remove the smallest item. void LeftistHeap::deleteMin() { Node *oldRoot = root; root = Merge(root->left, root->right); delete oldRoot; } // Function to remove the smallest item. void LeftistHeap::deleteMin(int &minItem) { if (isEmpty()) { cout << "Heap is Empty" << endl; return; } minItem = findMin(); deleteMin(); } // Function to test if the priority queue is logically empty. bool LeftistHeap::isEmpty()
  • 6. { return root == NULL; } // Function to test if the priority queue is logically full. bool LeftistHeap::isFull() { return false; } // Make the priority queue logically empty void LeftistHeap::makeEmpty() { reclaimMemory(root); root = NULL; } // Deep copy LeftistHeap &LeftistHeap::operator=(LeftistHeap &rhs) { if (this != &rhs) { makeEmpty(); root = clone(rhs.root); } return *this; } // Internal method to make the tree empty. void LeftistHeap::reclaimMemory(Node *t) { if (t != NULL){ reclaimMemory(t->left); reclaimMemory(t->right); delete t; } } // Internal method to clone subtree. Node *LeftistHeap::clone(Node *t) { if (t == NULL){ return NULL; } else{ return new Node(t->val, clone(t->left), clone(t->right), t->dist); } } // Driver program
  • 7. int main() { LeftistHeap h; LeftistHeap h1; LeftistHeap h2; int x; int arr[] = {1, 5, 7, 10, 15}; int arr1[] = {22, 75}; h.Insert(arr[0]); h.Insert(arr[1]); h.Insert(arr[2]); h.Insert(arr[3]); h.Insert(arr[4]); h1.Insert(arr1[0]); h1.Insert(arr1[1]); h.deleteMin(x); cout << x << endl; h1.deleteMin(x); cout << x << endl; h.Merge(h1); h2 = h; h2.deleteMin(x); cout << x << endl; return 0; } Output 1 22 5