Open In App

Print all nodes less than a value x in a Min Heap.

Last Updated : 24 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary min heap and a value x, print all the binary heap nodes having value less than the given value x.

Examples : Consider the below min heap as
        common input two both below examples.
                   2
                /     \
               3        15
            /    \     / \
           5       4  45  80
          / \     / \
         6   150 77 120

Input  : x = 15        
Output : 2 3 5 6 4

Input  : x = 80
Output : 2 3 5 6 4 77 15 45

The idea is to do a preorder traversal of the given Binary heap. While doing preorder traversal, if the value of a node is greater than the given value x, we return to the previous recursive call. Because all children nodes in a min heap are greater than the parent node. Otherwise we print current node and recur for its children. 

Implementation:

C++




// A C++ program to print all values
// smaller than a given value in Binary
// Heap
#include <bits/stdc++.h>
using namespace std;
 
// A class for Min Heap
class MinHeap {
    // pointer to array of elements in heap
    int* harr;
 
    // maximum possible size of min heap
    int capacity;
    int heap_size; // Current no. of elements.
public:
    // Constructor
    MinHeap(int capacity);
 
    // to heapify a subtree with root at
    // given index
    void MinHeapify(int);
 
    int parent(int i) { return (i - 1) / 2; }
    int left(int i) { return (2 * i + 1); }
    int right(int i) { return (2 * i + 2); }
 
    // Inserts a new key 'k'
    void insertKey(int k);
 
    // Function to print all nodes smaller than k
    void printSmallerThan(int k, int pos);
};
 
// Function to print all elements smaller than k
void MinHeap::printSmallerThan(int x, int pos = 0)
{
    /* Make sure item exists */
    if (pos >= heap_size)
        return;
 
    if (harr[pos] >= x) {
        /* Skip this node and its descendants,
          as they are all >= x . */
        return;
    }
 
    cout << harr[pos] << " ";
 
    printSmallerThan(x, left(pos));
    printSmallerThan(x, right(pos));
}
 
// Constructor: Builds a heap from a given
// array a[] of given size
MinHeap::MinHeap(int cap)
{
    heap_size = 0;
    capacity = cap;
    harr = new int[cap];
}
 
// Inserts a new key 'k'
void MinHeap::insertKey(int k)
{
    if (heap_size == capacity) {
        cout << "\nOverflow: Could not insertKey\n";
        return;
    }
 
    // First insert the new key at the end
    heap_size++;
    int i = heap_size - 1;
    harr[i] = k;
 
    // Fix the min heap property if it is violated
    while (i != 0 && harr[parent(i)] > harr[i]) {
        swap(harr[i], harr[parent(i)]);
        i = parent(i);
    }
}
 
// A recursive method to heapify a subtree with
// root at given index. This method assumes that
// the subtrees are already heapified
void MinHeap::MinHeapify(int i)
{
    int l = left(i);
    int r = right(i);
    int smallest = i;
    if (l < heap_size && harr[l] < harr[i])
        smallest = l;
    if (r < heap_size && harr[r] < harr[smallest])
        smallest = r;
    if (smallest != i) {
        swap(harr[i], harr[smallest]);
        MinHeapify(smallest);
    }
}
 
// Driver program to test above functions
int main()
{
    MinHeap h(50);
    h.insertKey(3);
    h.insertKey(2);
    h.insertKey(15);
    h.insertKey(5);
    h.insertKey(4);
    h.insertKey(45);
    h.insertKey(80);
    h.insertKey(6);
    h.insertKey(150);
    h.insertKey(77);
    h.insertKey(120);
 
    // Print all nodes smaller than 100.
    int x = 100;
    h.printSmallerThan(x);
 
    return 0;
}


Java




// A Java program to print all values
// smaller than a given value in Binary
// Heap
 
// A class for Min Heap
class MinHeap {
    // array of elements in heap
    int[] harr;
 
    // maximum possible size of min heap
    int capacity;
    int heap_size; // Current no. of elements.
 
    int parent(int i) { return (i - 1) / 2; }
    int left(int i) { return (2 * i + 1); }
    int right(int i) { return (2 * i + 2); }
 
    // Function to print all elements smaller than k
    void printSmallerThan(int x, int pos)
    {
        /* Make sure item exists */
        if (pos >= heap_size)
            return;
 
        if (harr[pos] >= x) {
            /* Skip this node and its descendants,
            as they are all >= x . */
            return;
        }
 
        System.out.print(harr[pos] + " ");
 
        printSmallerThan(x, left(pos));
        printSmallerThan(x, right(pos));
    }
 
    // Constructor: Builds a heap of given size
    public MinHeap(int cap)
    {
        heap_size = 0;
        capacity = cap;
        harr = new int[cap];
    }
 
    // Inserts a new key 'k'
    void insertKey(int k)
    {
        if (heap_size == capacity) {
            System.out.println("Overflow: Could not insertKey");
            return;
        }
 
        // First insert the new key at the end
        heap_size++;
        int i = heap_size - 1;
        harr[i] = k;
 
        // Fix the min heap property if it is violated
        while (i != 0 && harr[parent(i)] > harr[i]) {
            swap(i, parent(i));
            i = parent(i);
        }
    }
 
    // A utility function to swap two elements
    void swap(int x, int y)
    {
        int temp = harr[x];
        harr[x] = harr[y];
        harr[y] = temp;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        MinHeap h = new MinHeap(15);
        h.insertKey(3);
        h.insertKey(2);
        h.insertKey(15);
        h.insertKey(5);
        h.insertKey(4);
        h.insertKey(45);
        h.insertKey(80);
        h.insertKey(6);
        h.insertKey(150);
        h.insertKey(77);
        h.insertKey(120);
 
        // Print all nodes smaller than 100.
        int x = 100;
        h.printSmallerThan(x, 0);
    }
};
 
// This code is contributed by shubham96301


Python3




# A Python program to print all values
# smaller than a given value in Binary
# Heap
 
# A class for Min Heap
class MinHeap:
    # pointer to array of elements in heap
    harr = []
 
    # maximum possible size of min heap
    capacity = 0
    heap_size = 0  # Current no. of elements.
 
    # Constructor
    def __init__(self, capacity):
        self.heap_size = 0
        self.capacity = capacity
        self.harr = [0] * capacity
 
    # to heapify a subtree with root at
    # given index
    def MinHeapify(self, i):
        l = self.left(i)
        r = self.right(i)
        smallest = i
        if l < self.heap_size and self.harr[l] < self.harr[i]:
            smallest = l
        if r < self.heap_size and self.harr[r] < self.harr[smallest]:
            smallest = r
        if smallest != i:
            self.harr[i], self.harr[smallest] = self.harr[smallest], self.harr[i]
            self.MinHeapify(smallest)
 
    def parent(self, i):
        return (i - 1) // 2
 
    def left(self, i):
        return (2 * i + 1)
 
    def right(self, i):
        return (2 * i + 2)
 
    # Inserts a new key 'k'
    def insertKey(self, k):
        if self.heap_size == self.capacity:
            print("\nOverflow: Could not insertKey\n")
            return
        # First insert the new key at the end
        self.heap_size += 1
        i = self.heap_size - 1
        self.harr[i] = k
        # Fix the min heap property if it is violated
        while i != 0 and self.harr[self.parent(i)] > self.harr[i]:
            self.harr[i], self.harr[self.parent(i)] = self.harr[self.parent(i)], self.harr[i]
            i = self.parent(i)
 
    # Function to print all nodes smaller than k
    def printSmallerThan(self, x, pos=0):
        """
        Make sure item exists
        """
        if pos >= self.heap_size:
            return
        if self.harr[pos] >= x:
            """
            Skip this node and its descendants,
            as they are all >= x .
            """
            return
        print(self.harr[pos], end=" ")
        self.printSmallerThan(x, self.left(pos))
        self.printSmallerThan(x, self.right(pos))
 
 
# Driver program to test above functions
def main():
    h = MinHeap(50)
    h.insertKey(3)
    h.insertKey(2)
    h.insertKey(15)
    h.insertKey(5)
    h.insertKey(4)
    h.insertKey(45)
    h.insertKey(80)
    h.insertKey(6)
    h.insertKey(150)
    h.insertKey(77)
    h.insertKey(120)
 
    # Print all nodes smaller than 100.
    x = 100
    h.printSmallerThan(x)
 
if __name__ == "__main__":
    main()
 
    # This code is contributed by vikramshirsath177.


C#




// A C# program to print all values
// smaller than a given value in
// Binary Heap
using System;
 
// A class for Min Heap
public class MinHeap
{
    // array of elements in heap
    int[] harr;
 
    // maximum possible size of min heap
    int capacity;
     
    // Current no. of elements
    int heap_size;
 
    int parent(int i) { return (i - 1) / 2; }
    int left(int i) { return (2 * i + 1); }
    int right(int i) { return (2 * i + 2); }
 
    // Function to print
    // all elements smaller than k
    void printSmallerThan(int x, int pos)
    {
        /* Make sure item exists */
        if (pos >= heap_size)
            return;
 
        if (harr[pos] >= x)
        {
            /* Skip this node and its descendants,
            as they are all >= x . */
            return;
        }
 
        Console.Write(harr[pos] + " ");
 
        printSmallerThan(x, left(pos));
        printSmallerThan(x, right(pos));
    }
 
    // Constructor: Builds a heap of given size
    public MinHeap(int cap)
    {
        heap_size = 0;
        capacity = cap;
        harr = new int[cap];
    }
 
    // Inserts a new key 'k'
    void insertKey(int k)
    {
        if (heap_size == capacity)
        {
            Console.WriteLine("Overflow: Could not insertKey");
            return;
        }
 
        // First insert the new key at the end
        heap_size++;
        int i = heap_size - 1;
        harr[i] = k;
 
        // Fix the min heap property
        // if it is violated
        while (i != 0 &&
               harr[parent(i)] > harr[i])
        {
            swap(i, parent(i));
            i = parent(i);
        }
    }
 
    // A utility function to swap two elements
    void swap(int x, int y)
    {
        int temp = harr[x];
        harr[x] = harr[y];
        harr[y] = temp;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        MinHeap h = new MinHeap(15);
        h.insertKey(3);
        h.insertKey(2);
        h.insertKey(15);
        h.insertKey(5);
        h.insertKey(4);
        h.insertKey(45);
        h.insertKey(80);
        h.insertKey(6);
        h.insertKey(150);
        h.insertKey(77);
        h.insertKey(120);
 
        // Print all nodes smaller than 100.
        int x = 100;
        h.printSmallerThan(x, 0);
    }
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
 
// A JavaScript program to print all values
// smaller than a given value in Binary
// Heap
 
// A class for Min Heap
class MinHeap {
 
    // Constructor: Builds a heap of given size
    constructor(capacity){
        this.harr = new Array(capacity); // array of elements in heap
        this.capacity = capacity; // maximum possible size of min heap
        this.heap_size = 0; // Current no. of elements.
    }
 
    parent(i) { return parseInt((i - 1) / 2); }
    left(i) { return (2 * i + 1); }
    right(i) { return (2 * i + 2); }
 
    // Function to print all elements smaller than k
    printSmallerThan(x, pos)
    {
        /* Make sure item exists */
        if (pos >= this.heap_size)
            return;
 
        if (this.harr[pos] >= x) {
            /* Skip this node and its descendants,
            as they are all >= x . */
            return;
        }
 
        document.write(this.harr[pos] , " ");
 
        this.printSmallerThan(x, this.left(pos));
        this.printSmallerThan(x, this.right(pos));
    }
 
    // A utility function to swap two elements
    swap(x, y)
    {
        let temp = this.harr[x];
        this.harr[x] = this.harr[y];
        this.harr[y] = temp;
    }
 
    // Inserts a new key 'k'
    insertKey(k)
    {
        if (this.heap_size == this.capacity) {
            System.out.println("Overflow: Could not insertKey");
            return;
        }
 
        // First insert the new key at the end
        this.heap_size++;
        let i = this.heap_size - 1;
        this.harr[i] = k;
 
        // Fix the min heap property if it is violated
        while (i != 0 && this.harr[this.parent(i)] > this.harr[i]) {
            this.swap(i, this.parent(i));
            i = this.parent(i);
        }
    }
 
}
 
// Driver code
 
let h = new MinHeap(15);
h.insertKey(3);
h.insertKey(2);
h.insertKey(15);
h.insertKey(5);
h.insertKey(4);
h.insertKey(45);
h.insertKey(80);
h.insertKey(6);
h.insertKey(150);
h.insertKey(77);
h.insertKey(120);
 
// Print all nodes smaller than 100.
let x = 100;
h.printSmallerThan(x, 0);
     
// This code is contributed by Shinjan Patra   
 
</script>


Output

2 3 5 6 4 77 15 45 80 

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



Previous Article
Next Article

Similar Reads

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
Find min and max values among all maximum leaf nodes from all possible Binary Max Heap
Given a positive integer N, the task is to find the largest and smallest elements, from the maximum leaf nodes of every possible binary max-heap formed by taking the first N natural numbers as the nodes' value of the binary max-heap. Examples: Input: N = 2Output: 1 1Explanation: There is only one maximum binary heap with the nodes {1, 2}: In the ab
7 min read
Convert Min Heap to Max Heap
Given an array representation of min Heap, convert it to max Heap. Examples: Input: arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9} 3 / \ 5 9 / \ / \ 6 8 20 10 / \ /12 18 9 Output: arr[] = {20, 18, 10, 12, 9, 9, 3, 5, 6, 8} 20 / \ 18 10 / \ / \ 12 9 9 3 / \ /5 6 8 Input: arr[] = {3, 4, 8, 11, 13}Output: arr[] = {13, 11, 8, 4, 3} Approach: To solve the p
10 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
Difference between Min Heap and Max Heap
A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Since a heap is a complete binary tree, a heap with N nodes has log N height. It is useful to remove the highest or lowest priority element. It is typically represented as an array. There are two types of Heaps in the data structure. Min-HeapIn a Min-Heap the
3 min read
Print all the leaf nodes of Binary Heap
Given an array of N elements which denotes the array representation of binary heap, the task is to find the leaf nodes of this binary heap. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 4 5 6 7 Explanation: 1 / \ 2 3 / \ / \ 4 5 6 7 Leaf nodes of the Binary Heap are: 4 5 6 7 Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Output: 6 7 8 9 10
7 min read
Node having maximum number of nodes less than its value in its subtree
Given a Binary Tree, the task is to find the node from the given tree which has the maximum number of nodes in its subtree with values less than the value of that node. In the case of multiple possible nodes with the same number of maximum nodes, then return any such node. Examples: Input: 4 / \ 6 10 / \ / \2 3 7 14 / 5 Output: 6Explanation:Node wi
10 min read
Count of alphabets having ASCII value less than and greater than k
Given a string, the task is to count the number of alphabets having ASCII values less than and greater than or equal to a given integer k. Examples: Input: str = "GeeksForGeeks", k = 90Output:3, 10G, F, G have ascii values less than 90.e, e, k, s, o, r, e, e, k, s have ASCII values greater than or equal to 90 Input: str = "geeksforgeeks", k = 90Out
11 min read
Count of subsets having sum of min and max element less than K
Given an integer array arr[] and an integer K, the task is to find the number of non-empty subsets S such that min(S) + max(S) &lt; K.Examples: Input: arr[] = {2, 4, 5, 7} K = 8 Output: 4 Explanation: The possible subsets are {2}, {2, 4}, {2, 4, 5} and {2, 5}Input:: arr[] = {2, 4, 2, 5, 7} K = 10 Output: 26 Approach Sort the input array first.Now u
5 min read
Minimize removals in given Array to make max less than twice of min
Given an integer array arr[]. The task is to minimize the number of removals required such that the maximum element in arr[] becomes less than twice the minimum. Examples Input: arr[] = {4, 6, 21, 7, 5, 9, 12}Output: The minimum number of removal operations is 4.Explanation: The newly trimmed array is [7, 5, 9] where 9 is max and 5 is min; 9 &lt; 2
9 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg