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 1Output: 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 at that level.
- Print the final array which gives the number of nodes for that level.
Below is the implementation of the above approach:
C++
// C++ program of the// above approach#include <bits/stdc++.h>using namespace std;// Stores the nodes to be deletedunordered_map<int, bool> mp;// Structure of a Tree nodestruct Node { int key; struct Node *left, *right;};// Function to create a new nodeNode* 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 levelvoid 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 traversalvoid 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 levelvoid 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 Codeint 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);} |
Java
// Java program of the// above approachimport java.util.*;class GFG{// Stores the nodes to be deletedstatic Map<Integer, Boolean> mp = new HashMap<Integer, Boolean>(); // Structure of a Tree nodestatic class Node { int key; Node left, right;};// Function to create a new nodestatic 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 levelstatic void calculateMin(Node root, Vector<Integer> levelMin){ Queue<Node> qt = new LinkedList<>(); qt.add(root); // Count is used to diffentiate // each level of the tree int count = 1; int min_v = Integer.MAX_VALUE; while (!qt.isEmpty()) { Node temp = qt.peek(); min_v = Math.min(min_v, temp.key); qt.remove(); if (temp.left != null) { qt.add(temp.left); } if (temp.right != null) { qt.add(temp.right); } count--; if (count == 0) { levelMin.add(min_v); min_v = Integer.MAX_VALUE; count = qt.size(); } }}// Function to check whether the nodes in// the level below it are smaller// by performing post order traversalstatic void findNodes(Node root, Vector<Integer> levelMin, 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.get(i)) { levelResult[i] += 1; } }}// Function to print count of// nodes from all lower levels// having values less than the// the nodes in the current levelstatic void printNodes(Node root){ Vector<Integer> levelMin = new Vector<Integer>(); calculateMin(root, levelMin); // Stores the number of levels int numLevels = levelMin.size(); // Stores the required count // of nodes for each level int []levelResult = new int[numLevels]; findNodes(root, levelMin, levelResult, 0); for (int i = 0; i < numLevels; i++) { System.out.print(levelResult[i] + " "); }}// Driver Codepublic static void main(String[] args){ /* 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);}}// This code is contributed by 29AjayKumar |
Python3
# Python3 program of the# above approachfrom collections import dequefrom sys import maxsize as INT_MAX# Stores the nodes to be deletedmp = dict()# Structure of a Tree nodeclass Node: def __init__(self, key): self.key = key self.left = None self.right = None# Function to find the min value# of node for each leveldef calculateMin(root: Node, levelMin: list) -> None: qt = deque() qt.append(root) # Count is used to diffentiate # each level of the tree count = 1 min_v = INT_MAX while (qt): temp = qt.popleft() min_v = min(min_v, temp.key) if (temp.left): qt.append(temp.left) if (temp.right): qt.append(temp.right) count -= 1 if (count == 0): levelMin.append(min_v) min_v = INT_MAX count = len(qt)# Function to check whether the nodes in# the level below it are smaller# by performing post order traversaldef findNodes(root: Node, levelMin: list, levelResult: list, level: int) -> None: if (root == None): 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 i in range(level): 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 leveldef printNodes(root: Node) -> None: levelMin = [] calculateMin(root, levelMin) # Stores the number of levels numLevels = len(levelMin) # Stores the required count # of nodes for each level levelResult = [0] * numLevels findNodes(root, levelMin, levelResult, 0) for i in range(numLevels): print(levelResult[i], end = " ")# Driver Codeif __name__ == "__main__": ''' 4 / \ 3 5 / \ / \ 10 2 3 1 ''' root = Node(4) root.left = Node(3) root.right = Node(5) root.right.left = Node(3) root.right.right = Node(1) root.left.left = Node(10) root.left.right = Node(2) printNodes(root)# This code is contributed by sanjeev2552 |
C#
// C# program of the// above approachusing System;using System.Collections.Generic;class GFG{// Stores the nodes to be deletedstatic Dictionary<int, Boolean> mp = new Dictionary<int, Boolean>();// Structure of a Tree nodeclass Node { public int key; public Node left, right;};// Function to create a new nodestatic 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 levelstatic void calculateMin(Node root, List<int> levelMin){ Queue<Node> qt = new Queue<Node>(); qt.Enqueue(root); // Count is used to diffentiate // each level of the tree int count = 1; int min_v = int.MaxValue; while (qt.Count != 0) { Node temp = qt.Peek(); min_v = Math.Min(min_v, temp.key); qt.Dequeue(); if (temp.left != null) { qt.Enqueue(temp.left); } if (temp.right != null) { qt.Enqueue(temp.right); } count--; if (count == 0) { levelMin.Add(min_v); min_v = int.MaxValue; count = qt.Count; } }}// Function to check whether the nodes in// the level below it are smaller// by performing post order traversalstatic void findNodes(Node root, List<int> levelMin, 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 levelstatic void printNodes(Node root){ List<int> levelMin = new List<int>(); calculateMin(root, levelMin); // Stores the number of levels int numLevels = levelMin.Count; // Stores the required count // of nodes for each level int []levelResult = new int[numLevels]; findNodes(root, levelMin, levelResult, 0); for(int i = 0; i < numLevels; i++) { Console.Write(levelResult[i] + " "); }}// Driver Codepublic static void Main(String[] args){/* 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);}}// This code is contributed by Amit Katiyar |
4 3 0
Time Complexity: O(N2)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Check if a path exists for a cell valued 1 to reach the bottom right corner of a Matrix before any cell valued 2
- Print all the nodes except the leftmost node in every level of the given binary tree
- Print all nodes except rightmost node of every level of the Binary Tree
- Print odd positioned nodes of odd levels in level order of the given binary tree
- Print even positioned nodes of even levels in level order of the given binary tree
- Print even positioned nodes of odd levels in level order of the given binary tree
- Print odd positioned nodes of even levels in level order of the given binary tree
- Difference between sum of even and odd valued nodes in a Binary Tree
- Minimum valued node having maximum depth in an N-ary Tree
- Print Levels of all nodes in a Binary Tree
- Print all nodes between two given levels in Binary Tree
- Maximum sum of leaf nodes among all levels of the given binary tree
- Print alternate nodes from all levels of a Binary Tree
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Level order traversal with direction change after every two levels | Recursive Approach
- Level order traversal with direction change after every two levels
- Swap Nodes in Binary tree of every k'th level
- Difference between sums of odd level and even level nodes of a Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

