
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to check heap is forming max heap or not in Python
Suppose we have a list representing a heap tree. As we know heap is a complete binary tree. We have to check whether the elements are forming max heap or not. As we know for max heap every element is larger than both of its children.
So, if the input is like nums = [8, 6, 4, 2, 0, 3], then the output will be True because, all elements are larger than their children.
To solve this, we will follow these steps −
- n := size of nums
- for i in range 0 to n - 1, do
- m := i * 2
- num := nums[i]
- if m + 1 < n, then
- if num < nums[m + 1], then
- return False
- if num < nums[m + 1], then
- if m + 2 < n, then
- if num < nums[m + 2], then
- return False
- if num < nums[m + 2], then
- return True
Example
Let us see the following implementation to get better understanding −
def solve(nums): n = len(nums) for i in range(n): m = i * 2 num = nums[i] if m + 1 < n: if num < nums[m + 1]: return False if m + 2 < n: if num < nums[m + 2]: return False return True nums = [8, 6, 4, 2, 0, 3] print(solve(nums))
Input
[8, 6, 4, 2, 0, 3]
Output
True
- Related Articles
- Is Max Heap in Python?
- Convert min Heap to max Heap in C++
- C++ Program to Implement Max Heap
- Max Heap in Java
- Convert BST to Max Heap in C++
- Heap queue (or heapq) in Python
- What is Heap queue (or heapq) in Python?
- Program to check points are forming convex hull or not in Python
- Program to check points are forming concave polygon or not in Python
- Python Program for Heap Sort
- Minimum element in a max heap in C++.
- Program to check linked list items are forming palindrome or not in Python
- Check if a given Binary Tree is Heap in Python
- Insertion into a Max Heap in Data Structure
- Deletion from a Max Heap in Data Structure

Advertisements