Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree

Given a Binary Tree, the task is for each level is to print the total number of nodes from all lower levels which are less than or equal to every node present at that level.

Examples:

Input: Below is the given tree:
                           4
                         /   \
                      3       5
                    /  \    /  \
                 10  2  3    1

Output: 4 3 0
Explanation:
Nodes in level 1 has 4 nodes as (3) in level 2 and (2, 3, 1) in level 3.
Nodes in level 2 has 3 nodes as (2, 3, 1) in level 3.
Nodes in level 3 does not have any level left below it.

Input: Below is the given tree:



                      4
                     /  \
                   7    9
                 /     /  \
               1    3    1


Output: 3 3 0

Approach: Follow the steps below to solve the problem:

Calculate the minimum value at every level using Level Order Traversal.
Perform Post Order Traversal on the tree and check for every node whether nodes computed in step 1 are greater than or equal to the node. If found to be true, increment count by one at that level, providing that particular level has the node present in the level below it whose value is less than or equal to all the nodes present in that level.
Print the final array which gives the number of nodes for that level.
Below is the implementation of the above approach:

// C++ program of the
// above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Stores the nodes to be deleted
unordered_map<int, bool> mp;
 
// Structure of a Tree node
struct Node {
    int key;
    struct Node *left, *right;
};
 
// Function to create a new node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}
 
// Function to find the min value
// of node for each level
void calculateMin(Node* root,
                  vector<int>& levelMin)
{
    queue<Node*> qt;
    qt.push(root);
 
    // Count is used to diffentiate
    // each level of the tree
    int count = 1;
    int min_v = INT_MAX;
    while (!qt.empty()) {
 
        Node* temp = qt.front();
 
        min_v = min(min_v, temp->key);
 
        qt.pop();
 
        if (temp->left) {
            qt.push(temp->left);
        }
        if (temp->right) {
            qt.push(temp->right);
        }
        count--;
        if (count == 0) {
            levelMin.push_back(min_v);
            min_v = INT_MAX;
            count = qt.size();
        }
    }
}
 
// Function to check whether the nodes in
// the level below it are smaller
// by performing post order traversal
void findNodes(Node* root, vector<int>& levelMin,
               vector<int>& levelResult, int level)
{
    if (root == NULL)
        return;
 
    // Traverse the left subtree
    findNodes(root->left, levelMin,
              levelResult, level + 1);
 
    // Traverse right subtree
    findNodes(root->right, levelMin,
              levelResult, level + 1);
 
    // Check from minimum values
    // computed at each level
    for (int i = 0; i < level; i++) {
        if (root->key <= levelMin[i]) {
            levelResult[i] += 1;
        }
    }
}
 
// Function to print count of
// nodes from all lower levels
// having values less than the
// the nodes in the current level
void printNodes(Node* root)
{
    vector<int> levelMin;
    calculateMin(root, levelMin);
 
    // Stores the number of levels
    int numLevels = levelMin.size();
 
    // Stores the required count
    // of nodes for each level
    vector<int> levelResult(numLevels, 0);
    findNodes(root, levelMin, levelResult, 0);
 
    for (int i = 0; i < numLevels; i++) {
        cout << levelResult[i] << " ";
    }
}
 
// Driver Code
int main()
{
    /*
              4
           /     \
           3        5
         /  \     /   \
       10    2   3     1
      */
 
    Node* root = newNode(4);
 
    root->left = newNode(3);
    root->right = newNode(5);
 
    root->right->left = newNode(3);
    root->right->right = newNode(1);
 
    root->left->left = newNode(10);
    root->left->right = newNode(2);
    printNodes(root);
}
Output:
4 3 0
Time Complexity: O(N2)
Auxiliary Space: O(1)

Comments

Popular posts from this blog

I get wrong characters when retreiving the message body of an email using TIdIMAP4.UIDRetrieveTextPeek2()

How to drop the all the 1's in a correlation matrix

Today Walkin 14th-Sept