Open In App

Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap

Last Updated : 26 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given the level order traversal of a Complete Binary Tree, determine whether the Binary Tree is a valid Min-Heap

Examples:

Input : level = [10, 15, 14, 25, 30]
Output : True
The tree of the given level order traversal is
                     10
                    /  \
                   15   14
                  /  \
                 25   30
We see that each parent has a value less than
its child, and hence satisfies the min-heap 
property
 
Input : level = [30, 56, 22, 49, 30, 51, 2, 67]
Output : False
The tree of the given level order traversal is
                         30
                      /      \
                    56         22
                 /      \     /   \
               49        30  51    2
              /
             67
We observe that at level 0, 30 > 22, and hence
min-heap property is not satisfied

We need to check whether each non-leaf node (parent) satisfies the heap property. For this, we check whether each parent (at index i) is smaller than its children (at indices 2*i+1 and 2*i+2, if the parent has two children). If only one child, we only check the parent against index 2*i+1.

C++




// C++ program to check if a given tree is
// Binary Heap or not
#include <bits/stdc++.h>
using namespace std;
 
// Returns true if given level order traversal
// is Min Heap.
bool isMinHeap(int level[], int n)
{
    // First non leaf node is at index (n/2-1).
    // Check whether each parent is greater than child
    for (int i=(n/2-1) ; i>=0 ; i--)
    {
        // Left child will be at index 2*i+1
        // Right child will be at index 2*i+2
        if (level[i] > level[2 * i + 1])
            return false;
 
        if (2*i + 2 < n)
        {
            // If parent is greater than right child
            if (level[i] > level[2 * i + 2])
                return false;
        }
    }
    return true;
}
 
// Driver code
int main()
{
    int level[] = {10, 15, 14, 25, 30};
    int n = sizeof(level)/sizeof(level[0]);
    if  (isMinHeap(level, n))
        cout << "True";
    else
        cout << "False";
    return 0;
}


Java




// Java program to check if a given tree is
// Binary Heap or not
import java.io.*;
import java.util.*;
 
public class detheap
{
    // Returns true if given level order traversal
    // is Min Heap.
    static boolean isMinHeap(int []level)
    {
        int n = level.length - 1;
 
        // First non leaf node is at index (n/2-1).
        // Check whether each parent is greater than child
        for (int i=(n/2-1) ; i>=0 ; i--)
        {
            // Left child will be at index 2*i+1
            // Right child will be at index 2*i+2
            if (level[i] > level[2 * i + 1])
                return false;
 
            if (2*i + 2 < n)
            {
                // If parent is greater than right child
                if (level[i] > level[2 * i + 2])
                   return false;
            }
        }
        return true;
    }
 
    // Driver code
    public static void main(String[] args)
                              throws IOException
    {
        // Level order traversal
        int[] level = new int[]{10, 15, 14, 25, 30};
 
        if  (isMinHeap(level))
            System.out.println("True");
        else
            System.out.println("False");
    }
}


Python3




# Python3 program to check if a given
# tree is Binary Heap or not
 
# Returns true if given level order
# traversal is Min Heap.
def isMinHeap(level, n):
     
    # First non leaf node is at index
    # (n/2-1). Check whether each parent
    # is greater than child
    for i in range(int(n / 2) - 1, -1, -1):
         
        # Left child will be at index 2*i+1
        # Right child will be at index 2*i+2
        if level[i] > level[2 * i + 1]:
            return False
 
        if 2 * i + 2 < n:
             
            # If parent is greater than right child
            if level[i] > level[2 * i + 2]:
                return False
    return True
 
# Driver code
if __name__ == '__main__':
    level = [10, 15, 14, 25, 30]
    n = len(level)
    if isMinHeap(level, n):
        print("True")
    else:
        print("False")
 
# This code is contributed by PranchalK


C#




// C# program to check if a given tree
// is Binary Heap or not
using System;
 
class GFG
{
// Returns true if given level
// order traversal is Min Heap.
public static bool isMinHeap(int[] level)
{
    int n = level.Length - 1;
 
    // First non leaf node is at
    // index (n/2-1). Check whether
    // each parent is greater than child
    for (int i = (n / 2 - 1) ; i >= 0 ; i--)
    {
        // Left child will be at index 2*i+1
        // Right child will be at index 2*i+2
        if (level[i] > level[2 * i + 1])
        {
            return false;
        }
 
        if (2 * i + 2 < n)
        {
            // If parent is greater than right child
            if (level[i] > level[2 * i + 2])
            {
            return false;
            }
        }
    }
    return true;
}
 
// Driver code
public static void Main(string[] args)
{
    // Level order traversal
    int[] level = new int[]{10, 15, 14, 25, 30};
 
    if (isMinHeap(level))
    {
        Console.WriteLine("True");
    }
    else
    {
        Console.WriteLine("False");
    }
}
}
 
// This code is contributed by Shrikant13


PHP




<?php
// PHP program to check if a given tree
// is Binary Heap or not
 
// Returns true if given level order
// traversal is Min Heap.
function isMinHeap($level, $n)
{
    // First non leaf node is at index
    // (n/2-1). Check whether each parent
    // is greater than child
    for ($i = ($n / 2 - 1); $i >= 0; $i--)
    {
        // Left child will be at index 2*i+1
        // Right child will be at index 2*i+2
        if ($level[$i] > $level[2 * $i + 1])
            return false;
 
        if (2 * $i + 2 < $n)
        {
            // If parent is greater than right child
            if ($level[$i] > $level[2 * $i + 2])
                return false;
        }
    }
    return true;
}
 
// Driver code
$level = array(10, 15, 14, 25, 30);
$n = sizeof($level);
if (isMinHeap($level, $n))
    echo "True";
else
    echo "False";
 
// This code is contributed
// by Akanksha Rai


Javascript




<script>
 
// JavaScript program to check if a given tree
// is Binary Heap or not
 
// Returns true if given level
// order traversal is Min Heap.
function isMinHeap(level)
{
    var n = level.length - 1;
 
    // First non leaf node is at
    // index (n/2-1). Check whether
    // each parent is greater than child
    for(var i = (n / 2 - 1) ; i >= 0 ; i--)
    {
        // Left child will be at index 2*i+1
        // Right child will be at index 2*i+2
        if (level[i] > level[2 * i + 1])
        {
            return false;
        }
 
        if (2 * i + 2 < n)
        {
            // If parent is greater than right child
            if (level[i] > level[2 * i + 2])
            {
            return false;
            }
        }
    }
    return true;
}
 
// Driver code
// Level order traversal
var level = [10, 15, 14, 25, 30];
if (isMinHeap(level))
{
    document.write("True");
}
else
{
    document.write("False");
}
 
 
</script>


Output

True

Time Complexity: O(n)
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Pre Order, Post Order and In Order traversal of a Binary Tree in one traversal | (Using recursion)
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order in one iteration. Examples: Input: Output: Pre Order: 1 2 4 5 3 6 7 Post Order: 4 5 2 6 7 3 1 In Order: 4 2 5 1 6 3 7 Input: Output: Pre Order: 1 2 4 8 12 5 9 3 6 7 10 11 Post Order: 12 8 4 9 5 2 6 10 11 7 3 1 In Order: 8 12 4 2 9 5 1 6
9 min read
Level order traversal of Binary Tree using Morris Traversal
Given a binary tree, the task is to traverse the Binary Tree in level order fashion.Examples: Input: 1 / \ 2 3 Output: 1 2 3 Input: 5 / \ 2 3 \ 6 Output: 5 2 3 6 Approach: The idea is to use Morris Preorder Traversal to traverse the tree in level order traversal.Observations: There are mainly two observations for the traversal of the tree using Mor
11 min read
Heap Sort for decreasing order using min heap
Given an array of elements, sort the array in decreasing order using min heap. Examples: Input : arr[] = {5, 3, 10, 1} Output : arr[] = {10, 5, 3, 1} Input : arr[] = {1, 50, 100, 25} Output : arr[] = {100, 50, 25, 1} Prerequisite: Heap sort using min heap. Algorithm : Build a min heap from the input data. At this point, the smallest item is stored
13 min read
Flatten Binary Tree in order of Level Order Traversal
Given a Binary Tree, the task is to flatten it in order of Level order traversal of the tree. In the flattened binary tree, the left node of all the nodes must be NULL.Examples: Input: 1 / \ 5 2 / \ / \ 6 4 9 3 Output: 1 5 2 6 4 9 3 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 1 2 3 4 5 Approach: We will solve this problem by simulating the Level order travers
7 min read
Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
Given a binary tree, print it vertically. The following example illustrates vertical order traversal. 1 / \ 2 3 / \ / \ 4 5 6 7 \ \ 8 9 The output of print this tree vertically will be: 4 2 1 5 6 3 8 7 9 We have discussed an efficient approach in below post.Print a Binary Tree in Vertical Order | Set 2 (Hashmap based Method)The above solution uses
10 min read
Difference between Binary Heap, Binomial Heap and Fibonacci Heap
Binary Heap:A Binary Heap is a Binary Tree with following properties. It’s a complete binary tree i.e., all levels are completely filled except possibly the last level and the last level has all keys as left as possible. This property of Binary Heap makes them suitable to be stored in an array. A Binary Heap is either Min Heap or Max Heap. In a Min
2 min read
Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
Given a Binary Search Tree, the task is to print the nodes of the BST in the following order: If the BST contains levels numbered from 1 to N then, the printing order is level 1, level N, level 2, level N - 1, and so on.The top-level order (1, 2, …) nodes are printed from left to right, while the bottom level order (N, N-1, ...) nodes are printed f
15+ min read
Check if the given array can represent Level Order Traversal of Binary Search Tree
Given an array of size n. The problem is to check whether the given array can represent the level order traversal of a Binary Search Tree or not. Examples: Input : arr[] = {7, 4, 12, 3, 6, 8, 1, 5, 10} Output : Yes For the given arr[] the Binary Search Tree is: 7 / \ 4 12 / \ / 3 6 8 / / \ 1 5 10 Input : arr[] = {11, 6, 13, 5, 12, 10} Output : No T
12 min read
Insertion in n-ary tree in given order and Level order traversal
Given a set of parent nodes where the index of the array is the child of each Node value, the task is to insert the nodes as a forest(multiple trees combined together) where each parent could have more than two children. After inserting the nodes, print each level in a sorted format. Example: Input: arr[] = {5, 3, -1, 2, 5, 3} Output:-1 231 5Input:
10 min read
Check if the level order traversal of a Binary Tree results in a palindrome
Given a binary tree and the task if to check if it's level order traversal results in a palindrome or not.Examples: Input: Output: Yes RADAR is the level order traversal of the given tree which is a palindrome.Input: Output: No Approach: Traverse the Binary Tree in level order and store the nodes in a stack.Traverse the Binary Tree in level order o
10 min read
Article Tags :
Practice Tags :