SlideShare une entreprise Scribd logo
1  sur  11
Heap Tree
A Heap is a special Tree-based data structure in which the tree is a complete binary
tree
Types of Heap Data Structure
Generally, Heaps can be of two types:
1. Max-Heap: In a Max-Heap the key present at the root node must be
greatest among the keys present at all of its children. The same property
must be recursively true for all sub-trees in that Binary Tree.
2. Min-Heap: In a Min-Heap the key present at the root node must be
minimum among the keys present at all of its children. The same
property must be recursively true for all sub-trees in that Binary Tree.
Operations of Heap Data Structure:
• Heapify: a process of creating a heap from an array.
• Insertion: process to insert an element in existing heap time
complexity O (log N).
• Deletion: deleting the top element of the heap or the highest priority
element, and then organizing the heap and returning the element with
time complexity O (log N).
• Peek: to check or find the most prior element in the heap, (max or min
element for max and min heap).
Heapify:
Heapify is the process of creating a heap data structure from a binary tree. It is
used to create a Min-Heap or a Max-Heap.
1. Let the input array be:
0 1 2 3 4
2. Create a Complete Binary Tree from the array.
3. Start from the first index of non-leaf node whose index is given by n/2-1.
3 9 2 1 4 5
4. Set current element i as largest.
5. The index of left child is given by 2i + 1 and the right child is given by 2i +
2. If leftChild is greater than CurrentElement (i.e., element at ith index),
set leftChildIndex as largest.
If rightChild is greater than element in largest,
set rightChildIndex as largest.
6. Swap largest with currentElement
7. Repeat steps 3-7 until the subtrees are also heapified.
For Max Heap
Algorithm:
Heapify (array, size, i)
Set i as largest
Leftchild=2i + 1
Rightchild =2i + 2
If leftchild > array[largest]
Set LeftChildIndex as largest
If rightchild > array[largest]
Set RightChildIndex as largest
Swap array[i] array[largest]
To create Max Heap:
MaxHeap (array, size)
Loop from the first index of non-leaf node down to zero
Call heapify
For Min Heap
Algorithm:
Heapify (array, size, i)
Set i as smallest
Leftchild=2i + 1
Rightchild =2i + 2
If leftchild < array[smallest]
Set LeftChildIndex as smallest
If rightchild < array[smallest]
Set RightChildIndex as smallest
Swap array[i] array[smallest]
To create Min Heap:
MaxHeap (array, size)
Loop from the first index of non-leaf node down to zero
Call heapify
Insert Elements into Heap
Algorithm for Insertion in Max Heap
• If there is no Node
• Create a newNode
• Else (a node already present)
• Insert the newNode at the end (last node from left to right)
• Heapify the array
1. Insert the new node at the end of the tree.
2. Heapify the tree.
For min Heap, the above algorithm is modified so that Parent node is always smaller than
newNode.
Delete Element from Heap:
Algorithm for deletion in Max heap
• If nodeToBeDeleted is the leafNode
• Remove the Node
• Else swap nodeToBeDeleted with the last leafNode
• Remove nodeToBeDeleted
• Heapify the Array
1. Select the Element to be deleted
2. Swap it with the last element
3. Remove the last element.
4. Heapify the tree
Peek (Find max/min)
Peek operation returns the maximum element from Max Heap or minimum
element from Min Heap without deleting the node.
For both Max heap and Min Heap
Return RootNode;
Program:
For Max Heap:
#include <iostream>
#include <vector>
using namespace std;
void swap(int* a, int* b)
{
int temp = *b;
*b = *a;
*a = temp;
}
void heapify(vector<int>& hT, int i)
{
int size = hT.size();
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < size && hT[l] > hT[largest])
largest = l;
if (r < size && hT[r] > hT[largest])
largest = r;
if (largest != i)
{
swap(&hT[i], &hT[largest]);
heapify(hT, largest);
}
}
void insert(vector<int>& hT, int newNum)
{
int size = hT.size();
if (size == 0)
{
hT.push_back(newNum);
}
else
{
hT.push_back(newNum);
for (int i = size / 2 - 1; i >= 0; i--)
{
heapify(hT, i);
}
}
}
void deleteNode(vector<int>& hT, int num)
{
int size = hT.size();
int i;
for (i = 0; i < size; i++)
{
if (num == hT[i])
break;
}
swap(&hT[i], &hT[size - 1]);
hT.pop_back();
for (int i = size / 2 - 1; i >= 0; i--)
{
heapify(hT, i);
}
}
void printArray(vector<int>& hT)
{
for (int i = 0; i < hT.size(); ++i)
cout << hT[i] << " ";
cout << "n";
}
void maxElement(vector<int>& hT)
{
cout << "nMaximum Element=t" << hT[0];
}
int main()
{
vector<int> heapTree;
insert(heapTree, 3);
insert(heapTree, 4);
insert(heapTree, 9);
insert(heapTree, 5);
insert(heapTree, 2);
cout << "Max-Heap array: ";
printArray(heapTree);
maxElement(heapTree);
deleteNode(heapTree, 4);
cout << "nAfter deleting an element: ";
printArray(heapTree);
}
Output:
For Min Heap:
#include <iostream>
#include <vector>
using namespace std;
void swap(int* a, int* b)
{
int temp = *b;
*b = *a;
*a = temp;
}
void heapify(vector<int>& hT, int i)
{
int size = hT.size();
int smallest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < size && hT[l] < hT[smallest])
smallest = l;
if (r < size && hT[r] < hT[smallest])
smallest = r;
if (smallest != i)
{
swap(&hT[i], &hT[smallest]);
heapify(hT, smallest);
}
}
void insert(vector<int>& hT, int newNum)
{
int size = hT.size();
if (size == 0)
{
hT.push_back(newNum);
}
else
{
hT.push_back(newNum);
for (int i = size / 2 - 1; i >= 0; i--)
{
heapify(hT, i);
}
}
}
void deleteNode(vector<int>& hT, int num)
{
int size = hT.size();
int i;
for (i = 0; i < size; i++)
{
if (num == hT[i])
break;
}
swap(&hT[i], &hT[size - 1]);
hT.pop_back();
for (int i = size / 2 - 1; i >= 0; i--)
{
heapify(hT, i);
}
}
void printArray(vector<int>& hT)
{
for (int i = 0; i < hT.size(); ++i)
cout << hT[i] << " ";
cout << "n";
}
void minElement(vector<int>& hT)
{
cout << "nMinimum Element=t" << hT[0];
}
int main()
{
vector<int> heapTree;
insert(heapTree, 3);
insert(heapTree, 4);
insert(heapTree, 9);
insert(heapTree, 5);
insert(heapTree, 2);
cout << "Min-Heap array: ";
printArray(heapTree);
minElement(heapTree);
deleteNode(heapTree, 4);
cout << "nAfter deleting an element: ";
printArray(heapTree);
}
Output:

Contenu connexe

Tendances

Threaded Binary Tree
Threaded Binary TreeThreaded Binary Tree
Threaded Binary Treekhabbab_h
 
Applications of stack
Applications of stackApplications of stack
Applications of stackeShikshak
 
Indexing structure for files
Indexing structure for filesIndexing structure for files
Indexing structure for filesZainab Almugbel
 
Stack data structure
Stack data structureStack data structure
Stack data structureTech_MX
 
Bubble sort | Data structure |
Bubble sort | Data structure |Bubble sort | Data structure |
Bubble sort | Data structure |MdSaiful14
 
Integrity Constraints
Integrity ConstraintsIntegrity Constraints
Integrity Constraintsmadhav bansal
 
Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Anand Ingle
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ pptKumar
 
introduction to_trees
introduction to_treesintroduction to_trees
introduction to_treesDanish Aakash
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Janki Shah
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc csKALAISELVI P
 

Tendances (20)

Threaded Binary Tree
Threaded Binary TreeThreaded Binary Tree
Threaded Binary Tree
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
 
Indexing structure for files
Indexing structure for filesIndexing structure for files
Indexing structure for files
 
B and B+ tree
B and B+ treeB and B+ tree
B and B+ tree
 
B-Tree
B-TreeB-Tree
B-Tree
 
Linked lists
Linked listsLinked lists
Linked lists
 
Linked list
Linked listLinked list
Linked list
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
stack & queue
stack & queuestack & queue
stack & queue
 
Bubble sort | Data structure |
Bubble sort | Data structure |Bubble sort | Data structure |
Bubble sort | Data structure |
 
Queues
QueuesQueues
Queues
 
Integrity Constraints
Integrity ConstraintsIntegrity Constraints
Integrity Constraints
 
Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
Hash table
Hash tableHash table
Hash table
 
introduction to_trees
introduction to_treesintroduction to_trees
introduction to_trees
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
 
sorting and its types
sorting and its typessorting and its types
sorting and its types
 
Chapter 7 - Deadlocks
Chapter 7 - DeadlocksChapter 7 - Deadlocks
Chapter 7 - Deadlocks
 

Similaire à Heap Tree.pdf

data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3infanciaj
 
Analysis of Algorithms-Heapsort
Analysis of Algorithms-HeapsortAnalysis of Algorithms-Heapsort
Analysis of Algorithms-HeapsortReetesh Gupta
 
Describe a data structure that supports both removeMin() and rem.pdf
Describe a data structure that supports both removeMin() and rem.pdfDescribe a data structure that supports both removeMin() and rem.pdf
Describe a data structure that supports both removeMin() and rem.pdfarihantstoneart
 
Heap Sort 1053.pptx
Heap Sort 1053.pptxHeap Sort 1053.pptx
Heap Sort 1053.pptxZainiXh
 
USING JAVAThere are at least two types of nearly sorted array.pdf
USING JAVAThere are at least two types of nearly sorted array.pdfUSING JAVAThere are at least two types of nearly sorted array.pdf
USING JAVAThere are at least two types of nearly sorted array.pdflohithkart
 
Find attached the code to implement the following two functions- 1- In.pdf
Find attached the code to implement the following two functions- 1- In.pdfFind attached the code to implement the following two functions- 1- In.pdf
Find attached the code to implement the following two functions- 1- In.pdfJustinamEOgdend
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithmsmultimedia9
 
DataStructure Concepts-HEAP,HASH,Graph
DataStructure Concepts-HEAP,HASH,GraphDataStructure Concepts-HEAP,HASH,Graph
DataStructure Concepts-HEAP,HASH,GraphDurgadevi palani
 
Complete the classes shown below 1. The MinHeap Class Write necessa.pdf
Complete the classes shown below 1. The MinHeap Class Write necessa.pdfComplete the classes shown below 1. The MinHeap Class Write necessa.pdf
Complete the classes shown below 1. The MinHeap Class Write necessa.pdfamericanopticalscbe
 
CS-102 Course_ Binary Tree Lectures .pdf
CS-102 Course_ Binary Tree Lectures .pdfCS-102 Course_ Binary Tree Lectures .pdf
CS-102 Course_ Binary Tree Lectures .pdfssuser034ce1
 

Similaire à Heap Tree.pdf (20)

Heaps
HeapsHeaps
Heaps
 
Heaps
HeapsHeaps
Heaps
 
4 heapsort pq
4 heapsort pq4 heapsort pq
4 heapsort pq
 
Heapsort using Heap
Heapsort using HeapHeapsort using Heap
Heapsort using Heap
 
Unit III Heaps.ppt
Unit III Heaps.pptUnit III Heaps.ppt
Unit III Heaps.ppt
 
Heap and heapsort
Heap and heapsortHeap and heapsort
Heap and heapsort
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
Analysis of Algorithms-Heapsort
Analysis of Algorithms-HeapsortAnalysis of Algorithms-Heapsort
Analysis of Algorithms-Heapsort
 
Describe a data structure that supports both removeMin() and rem.pdf
Describe a data structure that supports both removeMin() and rem.pdfDescribe a data structure that supports both removeMin() and rem.pdf
Describe a data structure that supports both removeMin() and rem.pdf
 
Heap Sort 1053.pptx
Heap Sort 1053.pptxHeap Sort 1053.pptx
Heap Sort 1053.pptx
 
USING JAVAThere are at least two types of nearly sorted array.pdf
USING JAVAThere are at least two types of nearly sorted array.pdfUSING JAVAThere are at least two types of nearly sorted array.pdf
USING JAVAThere are at least two types of nearly sorted array.pdf
 
Heap sort
Heap sortHeap sort
Heap sort
 
Find attached the code to implement the following two functions- 1- In.pdf
Find attached the code to implement the following two functions- 1- In.pdfFind attached the code to implement the following two functions- 1- In.pdf
Find attached the code to implement the following two functions- 1- In.pdf
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
Heap
HeapHeap
Heap
 
linkedlist.pptx
linkedlist.pptxlinkedlist.pptx
linkedlist.pptx
 
DataStructure Concepts-HEAP,HASH,Graph
DataStructure Concepts-HEAP,HASH,GraphDataStructure Concepts-HEAP,HASH,Graph
DataStructure Concepts-HEAP,HASH,Graph
 
Complete the classes shown below 1. The MinHeap Class Write necessa.pdf
Complete the classes shown below 1. The MinHeap Class Write necessa.pdfComplete the classes shown below 1. The MinHeap Class Write necessa.pdf
Complete the classes shown below 1. The MinHeap Class Write necessa.pdf
 
Heap sort
Heap sortHeap sort
Heap sort
 
CS-102 Course_ Binary Tree Lectures .pdf
CS-102 Course_ Binary Tree Lectures .pdfCS-102 Course_ Binary Tree Lectures .pdf
CS-102 Course_ Binary Tree Lectures .pdf
 

Dernier

Forensic Biology & Its biological significance.pdf
Forensic Biology & Its biological significance.pdfForensic Biology & Its biological significance.pdf
Forensic Biology & Its biological significance.pdfrohankumarsinghrore1
 
GBSN - Microbiology (Unit 3)
GBSN - Microbiology (Unit 3)GBSN - Microbiology (Unit 3)
GBSN - Microbiology (Unit 3)Areesha Ahmad
 
development of diagnostic enzyme assay to detect leuser virus
development of diagnostic enzyme assay to detect leuser virusdevelopment of diagnostic enzyme assay to detect leuser virus
development of diagnostic enzyme assay to detect leuser virusNazaninKarimi6
 
Zoology 5th semester notes( Sumit_yadav).pdf
Zoology 5th semester notes( Sumit_yadav).pdfZoology 5th semester notes( Sumit_yadav).pdf
Zoology 5th semester notes( Sumit_yadav).pdfSumit Kumar yadav
 
module for grade 9 for distance learning
module for grade 9 for distance learningmodule for grade 9 for distance learning
module for grade 9 for distance learninglevieagacer
 
Connaught Place, Delhi Call girls :8448380779 Model Escorts | 100% verified
Connaught Place, Delhi Call girls :8448380779 Model Escorts | 100% verifiedConnaught Place, Delhi Call girls :8448380779 Model Escorts | 100% verified
Connaught Place, Delhi Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 
Module for Grade 9 for Asynchronous/Distance learning
Module for Grade 9 for Asynchronous/Distance learningModule for Grade 9 for Asynchronous/Distance learning
Module for Grade 9 for Asynchronous/Distance learninglevieagacer
 
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune WaterworldsBiogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune WaterworldsSérgio Sacani
 
Call Girls Ahmedabad +917728919243 call me Independent Escort Service
Call Girls Ahmedabad +917728919243 call me Independent Escort ServiceCall Girls Ahmedabad +917728919243 call me Independent Escort Service
Call Girls Ahmedabad +917728919243 call me Independent Escort Serviceshivanisharma5244
 
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPirithiRaju
 
Introduction to Viruses
Introduction to VirusesIntroduction to Viruses
Introduction to VirusesAreesha Ahmad
 
GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)Areesha Ahmad
 
9999266834 Call Girls In Noida Sector 22 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 22 (Delhi) Call Girl Service9999266834 Call Girls In Noida Sector 22 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 22 (Delhi) Call Girl Servicenishacall1
 
High Profile 🔝 8250077686 📞 Call Girls Service in GTB Nagar🍑
High Profile 🔝 8250077686 📞 Call Girls Service in GTB Nagar🍑High Profile 🔝 8250077686 📞 Call Girls Service in GTB Nagar🍑
High Profile 🔝 8250077686 📞 Call Girls Service in GTB Nagar🍑Damini Dixit
 
Grade 7 - Lesson 1 - Microscope and Its Functions
Grade 7 - Lesson 1 - Microscope and Its FunctionsGrade 7 - Lesson 1 - Microscope and Its Functions
Grade 7 - Lesson 1 - Microscope and Its FunctionsOrtegaSyrineMay
 
Pests of mustard_Identification_Management_Dr.UPR.pdf
Pests of mustard_Identification_Management_Dr.UPR.pdfPests of mustard_Identification_Management_Dr.UPR.pdf
Pests of mustard_Identification_Management_Dr.UPR.pdfPirithiRaju
 
Sector 62, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 62, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 62, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 62, Noida Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 
chemical bonding Essentials of Physical Chemistry2.pdf
chemical bonding Essentials of Physical Chemistry2.pdfchemical bonding Essentials of Physical Chemistry2.pdf
chemical bonding Essentials of Physical Chemistry2.pdfTukamushabaBismark
 
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.Nitya salvi
 
Human & Veterinary Respiratory Physilogy_DR.E.Muralinath_Associate Professor....
Human & Veterinary Respiratory Physilogy_DR.E.Muralinath_Associate Professor....Human & Veterinary Respiratory Physilogy_DR.E.Muralinath_Associate Professor....
Human & Veterinary Respiratory Physilogy_DR.E.Muralinath_Associate Professor....muralinath2
 

Dernier (20)

Forensic Biology & Its biological significance.pdf
Forensic Biology & Its biological significance.pdfForensic Biology & Its biological significance.pdf
Forensic Biology & Its biological significance.pdf
 
GBSN - Microbiology (Unit 3)
GBSN - Microbiology (Unit 3)GBSN - Microbiology (Unit 3)
GBSN - Microbiology (Unit 3)
 
development of diagnostic enzyme assay to detect leuser virus
development of diagnostic enzyme assay to detect leuser virusdevelopment of diagnostic enzyme assay to detect leuser virus
development of diagnostic enzyme assay to detect leuser virus
 
Zoology 5th semester notes( Sumit_yadav).pdf
Zoology 5th semester notes( Sumit_yadav).pdfZoology 5th semester notes( Sumit_yadav).pdf
Zoology 5th semester notes( Sumit_yadav).pdf
 
module for grade 9 for distance learning
module for grade 9 for distance learningmodule for grade 9 for distance learning
module for grade 9 for distance learning
 
Connaught Place, Delhi Call girls :8448380779 Model Escorts | 100% verified
Connaught Place, Delhi Call girls :8448380779 Model Escorts | 100% verifiedConnaught Place, Delhi Call girls :8448380779 Model Escorts | 100% verified
Connaught Place, Delhi Call girls :8448380779 Model Escorts | 100% verified
 
Module for Grade 9 for Asynchronous/Distance learning
Module for Grade 9 for Asynchronous/Distance learningModule for Grade 9 for Asynchronous/Distance learning
Module for Grade 9 for Asynchronous/Distance learning
 
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune WaterworldsBiogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
 
Call Girls Ahmedabad +917728919243 call me Independent Escort Service
Call Girls Ahmedabad +917728919243 call me Independent Escort ServiceCall Girls Ahmedabad +917728919243 call me Independent Escort Service
Call Girls Ahmedabad +917728919243 call me Independent Escort Service
 
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
 
Introduction to Viruses
Introduction to VirusesIntroduction to Viruses
Introduction to Viruses
 
GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)
 
9999266834 Call Girls In Noida Sector 22 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 22 (Delhi) Call Girl Service9999266834 Call Girls In Noida Sector 22 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 22 (Delhi) Call Girl Service
 
High Profile 🔝 8250077686 📞 Call Girls Service in GTB Nagar🍑
High Profile 🔝 8250077686 📞 Call Girls Service in GTB Nagar🍑High Profile 🔝 8250077686 📞 Call Girls Service in GTB Nagar🍑
High Profile 🔝 8250077686 📞 Call Girls Service in GTB Nagar🍑
 
Grade 7 - Lesson 1 - Microscope and Its Functions
Grade 7 - Lesson 1 - Microscope and Its FunctionsGrade 7 - Lesson 1 - Microscope and Its Functions
Grade 7 - Lesson 1 - Microscope and Its Functions
 
Pests of mustard_Identification_Management_Dr.UPR.pdf
Pests of mustard_Identification_Management_Dr.UPR.pdfPests of mustard_Identification_Management_Dr.UPR.pdf
Pests of mustard_Identification_Management_Dr.UPR.pdf
 
Sector 62, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 62, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 62, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 62, Noida Call girls :8448380779 Model Escorts | 100% verified
 
chemical bonding Essentials of Physical Chemistry2.pdf
chemical bonding Essentials of Physical Chemistry2.pdfchemical bonding Essentials of Physical Chemistry2.pdf
chemical bonding Essentials of Physical Chemistry2.pdf
 
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
 
Human & Veterinary Respiratory Physilogy_DR.E.Muralinath_Associate Professor....
Human & Veterinary Respiratory Physilogy_DR.E.Muralinath_Associate Professor....Human & Veterinary Respiratory Physilogy_DR.E.Muralinath_Associate Professor....
Human & Veterinary Respiratory Physilogy_DR.E.Muralinath_Associate Professor....
 

Heap Tree.pdf

  • 1. Heap Tree A Heap is a special Tree-based data structure in which the tree is a complete binary tree Types of Heap Data Structure Generally, Heaps can be of two types: 1. Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of its children. The same property must be recursively true for all sub-trees in that Binary Tree. 2. Min-Heap: In a Min-Heap the key present at the root node must be minimum among the keys present at all of its children. The same property must be recursively true for all sub-trees in that Binary Tree. Operations of Heap Data Structure: • Heapify: a process of creating a heap from an array. • Insertion: process to insert an element in existing heap time complexity O (log N).
  • 2. • Deletion: deleting the top element of the heap or the highest priority element, and then organizing the heap and returning the element with time complexity O (log N). • Peek: to check or find the most prior element in the heap, (max or min element for max and min heap). Heapify: Heapify is the process of creating a heap data structure from a binary tree. It is used to create a Min-Heap or a Max-Heap. 1. Let the input array be: 0 1 2 3 4 2. Create a Complete Binary Tree from the array. 3. Start from the first index of non-leaf node whose index is given by n/2-1. 3 9 2 1 4 5
  • 3. 4. Set current element i as largest. 5. The index of left child is given by 2i + 1 and the right child is given by 2i + 2. If leftChild is greater than CurrentElement (i.e., element at ith index), set leftChildIndex as largest. If rightChild is greater than element in largest, set rightChildIndex as largest. 6. Swap largest with currentElement 7. Repeat steps 3-7 until the subtrees are also heapified. For Max Heap Algorithm: Heapify (array, size, i) Set i as largest Leftchild=2i + 1 Rightchild =2i + 2 If leftchild > array[largest] Set LeftChildIndex as largest If rightchild > array[largest] Set RightChildIndex as largest Swap array[i] array[largest]
  • 4. To create Max Heap: MaxHeap (array, size) Loop from the first index of non-leaf node down to zero Call heapify For Min Heap Algorithm: Heapify (array, size, i) Set i as smallest Leftchild=2i + 1 Rightchild =2i + 2 If leftchild < array[smallest] Set LeftChildIndex as smallest If rightchild < array[smallest] Set RightChildIndex as smallest Swap array[i] array[smallest] To create Min Heap: MaxHeap (array, size) Loop from the first index of non-leaf node down to zero Call heapify
  • 5. Insert Elements into Heap Algorithm for Insertion in Max Heap • If there is no Node • Create a newNode • Else (a node already present) • Insert the newNode at the end (last node from left to right) • Heapify the array 1. Insert the new node at the end of the tree. 2. Heapify the tree. For min Heap, the above algorithm is modified so that Parent node is always smaller than newNode.
  • 6. Delete Element from Heap: Algorithm for deletion in Max heap • If nodeToBeDeleted is the leafNode • Remove the Node • Else swap nodeToBeDeleted with the last leafNode • Remove nodeToBeDeleted • Heapify the Array 1. Select the Element to be deleted 2. Swap it with the last element
  • 7. 3. Remove the last element. 4. Heapify the tree Peek (Find max/min) Peek operation returns the maximum element from Max Heap or minimum element from Min Heap without deleting the node. For both Max heap and Min Heap Return RootNode;
  • 8. Program: For Max Heap: #include <iostream> #include <vector> using namespace std; void swap(int* a, int* b) { int temp = *b; *b = *a; *a = temp; } void heapify(vector<int>& hT, int i) { int size = hT.size(); int largest = i; int l = 2 * i + 1; int r = 2 * i + 2; if (l < size && hT[l] > hT[largest]) largest = l; if (r < size && hT[r] > hT[largest]) largest = r; if (largest != i) { swap(&hT[i], &hT[largest]); heapify(hT, largest); } } void insert(vector<int>& hT, int newNum) { int size = hT.size(); if (size == 0) { hT.push_back(newNum); } else { hT.push_back(newNum); for (int i = size / 2 - 1; i >= 0; i--) { heapify(hT, i); } } } void deleteNode(vector<int>& hT, int num) { int size = hT.size(); int i; for (i = 0; i < size; i++) { if (num == hT[i]) break; } swap(&hT[i], &hT[size - 1]);
  • 9. hT.pop_back(); for (int i = size / 2 - 1; i >= 0; i--) { heapify(hT, i); } } void printArray(vector<int>& hT) { for (int i = 0; i < hT.size(); ++i) cout << hT[i] << " "; cout << "n"; } void maxElement(vector<int>& hT) { cout << "nMaximum Element=t" << hT[0]; } int main() { vector<int> heapTree; insert(heapTree, 3); insert(heapTree, 4); insert(heapTree, 9); insert(heapTree, 5); insert(heapTree, 2); cout << "Max-Heap array: "; printArray(heapTree); maxElement(heapTree); deleteNode(heapTree, 4); cout << "nAfter deleting an element: "; printArray(heapTree); } Output:
  • 10. For Min Heap: #include <iostream> #include <vector> using namespace std; void swap(int* a, int* b) { int temp = *b; *b = *a; *a = temp; } void heapify(vector<int>& hT, int i) { int size = hT.size(); int smallest = i; int l = 2 * i + 1; int r = 2 * i + 2; if (l < size && hT[l] < hT[smallest]) smallest = l; if (r < size && hT[r] < hT[smallest]) smallest = r; if (smallest != i) { swap(&hT[i], &hT[smallest]); heapify(hT, smallest); } } void insert(vector<int>& hT, int newNum) { int size = hT.size(); if (size == 0) { hT.push_back(newNum); } else { hT.push_back(newNum); for (int i = size / 2 - 1; i >= 0; i--) { heapify(hT, i); } } } void deleteNode(vector<int>& hT, int num) { int size = hT.size(); int i; for (i = 0; i < size; i++) { if (num == hT[i]) break; } swap(&hT[i], &hT[size - 1]); hT.pop_back(); for (int i = size / 2 - 1; i >= 0; i--)
  • 11. { heapify(hT, i); } } void printArray(vector<int>& hT) { for (int i = 0; i < hT.size(); ++i) cout << hT[i] << " "; cout << "n"; } void minElement(vector<int>& hT) { cout << "nMinimum Element=t" << hT[0]; } int main() { vector<int> heapTree; insert(heapTree, 3); insert(heapTree, 4); insert(heapTree, 9); insert(heapTree, 5); insert(heapTree, 2); cout << "Min-Heap array: "; printArray(heapTree); minElement(heapTree); deleteNode(heapTree, 4); cout << "nAfter deleting an element: "; printArray(heapTree); } Output: