Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA Tutorial
  • Data Structures
  • Algorithms
  • Array
  • Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Searching
  • Sorting
  • Recursion
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Divide & Conquer
  • Mathematical
  • Geometric
  • Bitwise
  • Greedy
  • Backtracking
  • Branch and Bound
  • Matrix
  • Pattern Searching
  • Randomized
Open In App
Next Article:
Reading binary files in Python
Next article icon

Binary Heap in Python

Last Updated : 12 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A Binary Heap is a complete Binary Tree that is used to store data efficiently to get the max or min element based on its structure.

A Binary Heap is either a Min Heap or a Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in a Binary Heap. The same property must be recursively true for all nodes in the Binary Tree. Max Binary Heap is similar to MinHeap. 

Examples of Min Heap:

            10                       10
         /      \                 /         \  
     20     100        15           30  
   /                        /    \         /    \
30                     40   50   100   40

Binary Heap in Python

Implement a binary heap data structure in Python, which supports the following operations:

  • insert(key): Insert a new element into the heap.
  • delete_min(): Delete the minimum element from the heap.
  • get_min(): Get the minimum element from the heap without deleting it.
  • is_empty(): Check if the heap is empty.

Approach:

A binary heap is a complete binary tree where the value of each parent node is less than or equal to the values of its children. The minimum element is at the root. The main operations are insert and delete_min.

1. Insert Operation:

  • Add the new element at the end of the heap.
  • Restore the heap property by repeatedly swapping the new element with its parent until the heap property is restored.

2. Delete Minimum Operation:

  • Replace the root of the heap with the last element.
  • Restore the heap property by repeatedly swapping the new root with its smallest child until the heap property is restored.

3. Get Minimum Operation:

  • Return the root of the heap.

4. Check if the Heap is Empty:

  • Check if the length of the heap is 0.

Code

Python3
class BinaryHeap:     def __init__(self):         self.heap = []      def is_empty(self):         return len(self.heap) == 0      def insert(self, key):         self.heap.append(key)         self._heapify_up(len(self.heap) - 1)      def _heapify_up(self, index):         parent_index = (index - 1) // 2         while parent_index >= 0 and self.heap[parent_index] > self.heap[index]:             self.heap[parent_index], self.heap[index] = self.heap[index], self.heap[parent_index]             index = parent_index             parent_index = (index - 1) // 2      def get_min(self):         if self.is_empty():             return None         return self.heap[0]      def delete_min(self):         if self.is_empty():             return None          min_value = self.heap[0]         self.heap[0] = self.heap[-1]         self.heap.pop()         self._heapify_down(0)          return min_value      def _heapify_down(self, index):         left_child_index = 2 * index + 1         right_child_index = 2 * index + 2         smallest = index          if left_child_index < len(self.heap) and self.heap[left_child_index] < self.heap[smallest]:             smallest = left_child_index          if right_child_index < len(self.heap) and self.heap[right_child_index] < self.heap[smallest]:             smallest = right_child_index          if smallest != index:             self.heap[index], self.heap[smallest] = self.heap[smallest], self.heap[index]             self._heapify_down(smallest)   # Example Usage heap = BinaryHeap()  # Insert elements heap.insert(3) heap.insert(2) heap.insert(15) heap.insert(5) heap.insert(4) heap.insert(45)  print("Minimum element in the heap:", heap.get_min())  # Delete minimum element print("Deleted minimum element:", heap.delete_min())  print("Minimum element in the heap after deletion:", heap.get_min()) 

Output
Minimum element in the heap: 2 Deleted minimum element: 2 Minimum element in the heap after deletion: 3 



Next Article
Reading binary files in Python

S

srinam
Improve
Article Tags :
  • DSA
  • Python-DSA

Similar Reads

  • Binary Tree in Python
    Binary Tree is a non-linear and hierarchical data structure where each node has at most two children referred to as the left child and the right child. The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. Representation of Binary TreeEach node in a Binar
    9 min read
  • Reading binary files in Python
    Reading binary files means reading data that is stored in a binary format, which is not human-readable. Unlike text files, which store data as readable characters, binary files store data as raw bytes. Binary files store data as a sequence of bytes. Each byte can represent a wide range of values, fr
    6 min read
  • Binarytree Module in Python
    A binary tree is a data structure in which every node or vertex has at most two children. In Python, a binary tree can be represented in different ways with different data structures(dictionary, list) and class representations for a node. However, binarytree library helps to directly implement a bin
    6 min read
  • hex() function in Python
    hex() function in Python is used to convert an integer to its hexadecimal equivalent. It takes an integer as input and returns a string representing the number in hexadecimal format, starting with "0x" to indicate that it's in base-16. Example: [GFGTABS] Python a = 255 res = hex(a) print(res) [/GFGT
    2 min read
  • Binary Search Tree In Python
    A Binary search tree is a binary tree where the values of the left sub-tree are less than the root node and the values of the right sub-tree are greater than the value of the root node. In this article, we will discuss the binary search tree in Python. What is a Binary Search Tree(BST)?A Binary Sear
    11 min read
  • Binary Operation
    Binary Operation is an operation defined for any set S such that it takes two elements from S as input and produces a single element in S as output. As the name suggests, binary operations require at least two inputs as it is defined from the cartesian product of set to set itself. In this article,
    7 min read
  • Boolean Array in NumPy - Python
    The goal here is to work with Boolean arrays in NumPy, which contain only True or False values. Boolean arrays are commonly used for conditional operations, masking and filtering elements based on specific criteria. For example, given a NumPy array [1, 0, 1, 0, 1], we can create a Boolean array wher
    3 min read
  • Elias Delta Decoding in Python
    In this article, we are going to implement Elias Delta Decoding using python. Peter Elias devised the Elias delta code, which is a universal system for encoding positive integers. Syntax: Elias Delta Encoding(X)= Elias Gamma encoding (1+floor(log2(X))) + Binary representation of X without MSB. Appro
    2 min read
  • Python Boolean
    Python Boolean type is one of the built-in data types provided by Python, which represents one of the two values i.e. True or False. Generally, it is used to represent the truth values of the expressions. Python Boolean TypeBoolean value can be of two types only i.e. either True or False. The output
    7 min read
  • What is Binary Code?
    Two States the digital systems, and computers are written in its basic language. Binary code It is a digital encoding of an analog signal wherein it uses a two-symbol system, ‘0’ and ‘1’, to represent text, computer processor instructions, or any other data. A bit short for "binary digit", is the ba
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences