SlideShare a Scribd company logo
1 of 7
Download to read offline
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

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 ProgammingTraian Rebedea
 
Advanced s and s algorithm.ppt
Advanced s and s algorithm.pptAdvanced s and s algorithm.ppt
Advanced s and s algorithm.pptLegesseSamuel
 
03-data-structures.pdf
03-data-structures.pdf03-data-structures.pdf
03-data-structures.pdfNash229987
 
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.pdffunkybabyindia
 
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.docxfarrahkur54
 
(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.docxajoy21
 
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 noteAbdur Rouf
 
Quick and Heap Sort with examples
Quick and Heap Sort with examplesQuick and Heap Sort with examples
Quick and Heap Sort with examplesBst 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.docxfestockton
 
computer notes - Stack
computer notes - Stackcomputer notes - Stack
computer notes - Stackecomputernotes
 
signal and system Dirac delta functions (1)
signal and system Dirac delta functions (1)signal and system Dirac delta functions (1)
signal and system Dirac delta functions (1)iqbal ahmad
 

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
 
computer notes - Stack
computer notes - Stackcomputer notes - Stack
computer notes - Stack
 
Heaps & priority queues
Heaps & priority queuesHeaps & priority queues
Heaps & priority queues
 
signal and system Dirac delta functions (1)
signal and system Dirac delta functions (1)signal and system Dirac delta functions (1)
signal and system Dirac delta functions (1)
 

Recently uploaded

CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 

Recently uploaded (20)

Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 

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