Minimum no. of iterations to pass information to all nodes in the tree
Last Updated :
12 Jul, 2023
Given a very large n-ary tree. Where the root node has some information which it wants to pass to all of its children down to the leaves with the constraint that it can only pass the information to one of its children at a time (take it as one iteration).
Now in the next iteration the child node can transfer that information to only one of its children and at the same time instance the child’s parent i.e. root can pass the info to one of its remaining children. Continuing in this way we have to find the minimum no of iterations required to pass the information to all nodes in the tree.
Minimum no of iterations for tree below is 6. The root A first passes information to B. In next iteration, A passes information to E and B passes information to H and so on.
Step-wise Tree Traversal
We strongly recommend to minimize the browser and try this yourself first.
This can be done using Post Order Traversal. The idea is to consider height and children count on each and every node.
If a child node i takes ci iterations to pass info below its subtree, then its parent will take (ci + 1) iterations to pass info to subtree rooted at that child i.
If parent has more children, it will pass info to them in subsequent iterations. Let’s say children of a parent takes c1, c2, c3, c4, …, cn iterations to pass info in their own subtree, Now parent has to pass info to these n children one by one in n iterations. If parent picks child i in ith iteration, then parent will take (i + ci) iterations to pass info to child i and all it’s subtree.
In any iteration, when parent passes info a child i+1, children (1 to i) which got info from parent already in previous iterations, will pass info to further down in subsequent iterations, if any child (1 to i) has its own child further down.
To pass info to whole tree in minimum iterations, it needs to be made sure that bandwidth is utilized as efficiently as possible (i.e. maximum passable no of nodes should pass info further down in any iteration)
The best possible scenario would be that in nth iteration, n different nodes pass info to their child.
Nodes with height = 0: (Trivial case) Leaf node has no children (no information passing needed), so no of iterations would be ZERO.
Nodes with height = 1: Here node has to pass info to all the children one by one (all children are leaf node, so no more information passing further down). Since all children are leaf, node can pass info to any child in any order (pick any child who didn't receive the info yet). One iteration needed for each child and so no of iterations would be no of children.So node with height 1 with n children will take n iterations.
Take a counter initialized with ZERO, loop through all children and keep incrementing counter.
Nodes with height > 1: Let’s assume that there are n children (1 to n) of a node and minimum no iterations for all n children are c1, c2, ...., cn.
To make sure maximum no of nodes participate in info passing in any iteration, parent should 1st pass info to that child who will take maximum iteration to pass info further down in subsequent iterations. i.e. in any iteration, parent should choose the child who takes maximum iteration later on. It can be thought of as a greedy approach where parent choose that child 1st, who needs maximum no of iterations so that all subsequent iterations can be utilized efficiently.
If parent goes in any other fashion, then in the end, there could be some nodes which are done quite early, sitting idle and so bandwidth is not utilized efficiently in further iterations.
If there are two children i and j with minimum iterations ci and cj where ci > cj, then If parent picks child j 1st then no of iterations needed by parent to pass info to both children and their subtree would be:max (1 + cj, 2 + ci) = 2 + ci
If parent picks child i 1st then no of iterations needed by parent to pass info to both children and their subtree would be: max(1 + ci, 2 + cj) = 1 + ci (So picking ci gives better result than picking cj)
This tells that parent should always choose child i with max ci value in any iteration.
SO here greedy approach is:
sort all ci values decreasing order,
let’s say after sorting, values are c1 > c2 > c3 > .... > cn
take a counter c, set c = 1 + c1 (for child with maximum no of iterations)
for all children i from 2 to n, c = c + 1 + ci
then total no of iterations needed by parent is max(n, c)
Let minItr(A) be the minimum iteration needed to pass info from node A to it's all the sub-tree. Let child(A) be the count of all children for node A. So recursive relation would be:
1. Get minItr(B) of all children (B) of a node (A)
2. Sort all minItr(B) in descending order
3. Get minItr of A based on all minItr(B)
minItr(A) = child(A)
For children B from i = 0 to child(A)
minItr(A) = max ( minItr(A), minItr(B) + i + 1)Base cases would be:
If node is leaf, minItr = 0
If node's height is 1, minItr = children count
Following is the implementation of above idea.
C++
// C++ program to find minimum number of iterations to pass
// information from root to all nodes in an n-ary tree
#include<bits/stdc++.h>
using namespace std;
// A class to represent n-ary tree (Note that the implementation
// is similar to graph for simplicity of implementation
class NAryTree
{
int N; // No. of nodes in Tree
// Pointer to an array containing list of children
list<int> *adj;
// A function used by getMinIter(), it basically does postorder
void getMinIterUtil(int v, int minItr[]);
public:
NAryTree(int N); // Constructor
// function to add a child w to v
void addChild(int v, int w);
// The main function to find minimum iterations
int getMinIter();
static int compare(const void * a, const void * b);
};
NAryTree::NAryTree(int N)
{
this->N = N;
adj = new list<int>[N];
}
// To add a child w to v
void NAryTree::addChild(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
/* A recursive function to used by getMinIter(). This function
// mainly does postorder traversal and get minimum iteration of all children
// of node u, sort them in decreasing order and then get minimum iteration
// of node u
1. Get minItr(B) of all children (B) of a node (A)
2. Sort all minItr(B) in descending order
3. Get minItr of A based on all minItr(B)
minItr(A) = child(A) -->> child(A) is children count of node A
For children B from i = 0 to child(A)
minItr(A) = max ( minItr(A), minItr(B) + i + 1)
Base cases would be:
If node is leaf, minItr = 0
If node's height is 1, minItr = children count
*/
void NAryTree::getMinIterUtil(int u, int minItr[])
{
minItr[u] = adj[u].size();
int *minItrTemp = new int[minItr[u]];
int k = 0, tmp = 0;
// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for (i = adj[u].begin(); i!= adj[u].end(); ++i)
{
getMinIterUtil(*i, minItr);
minItrTemp[k++] = minItr[*i];
}
qsort(minItrTemp, minItr[u], sizeof (int), compare);
for (k = 0; k < adj[u].size(); k++)
{
tmp = minItrTemp[k] + k + 1;
minItr[u] = max(minItr[u], tmp);
}
delete[] minItrTemp;
}
// The function to do PostOrder traversal. It uses
// recursive getMinIterUtil()
int NAryTree::getMinIter()
{
// Set minimum iteration all the vertices as zero
int *minItr = new int[N];
int res = -1;
for (int i = 0; i < N; i++)
minItr[i] = 0;
// Start Post Order Traversal from Root
getMinIterUtil(0, minItr);
res = minItr[0];
delete[] minItr;
return res;
}
int NAryTree::compare(const void * a, const void * b)
{
return ( *(int*)b - *(int*)a );
}
// Driver function to test above functions
int main()
{
// TestCase 1
NAryTree tree1(17);
tree1.addChild(0, 1);
tree1.addChild(0, 2);
tree1.addChild(0, 3);
tree1.addChild(0, 4);
tree1.addChild(0, 5);
tree1.addChild(0, 6);
tree1.addChild(1, 7);
tree1.addChild(1, 8);
tree1.addChild(1, 9);
tree1.addChild(4, 10);
tree1.addChild(4, 11);
tree1.addChild(6, 12);
tree1.addChild(7, 13);
tree1.addChild(7, 14);
tree1.addChild(10, 15);
tree1.addChild(11, 16);
cout << "TestCase 1 - Minimum Iteration: "
<< tree1.getMinIter() << endl;
// TestCase 2
NAryTree tree2(3);
tree2.addChild(0, 1);
tree2.addChild(0, 2);
cout << "TestCase 2 - Minimum Iteration: "
<< tree2.getMinIter() << endl;
// TestCase 3
NAryTree tree3(1);
cout << "TestCase 3 - Minimum Iteration: "
<< tree3.getMinIter() << endl;
// TestCase 4
NAryTree tree4(6);
tree4.addChild(0, 1);
tree4.addChild(1, 2);
tree4.addChild(2, 3);
tree4.addChild(3, 4);
tree4.addChild(4, 5);
cout << "TestCase 4 - Minimum Iteration: "
<< tree4.getMinIter() << endl;
// TestCase 5
NAryTree tree5(6);
tree5.addChild(0, 1);
tree5.addChild(0, 2);
tree5.addChild(2, 3);
tree5.addChild(2, 4);
tree5.addChild(2, 5);
cout << "TestCase 5 - Minimum Iteration: "
<< tree5.getMinIter() << endl;
// TestCase 6
NAryTree tree6(6);
tree6.addChild(0, 1);
tree6.addChild(0, 2);
tree6.addChild(2, 3);
tree6.addChild(2, 4);
tree6.addChild(3, 5);
cout << "TestCase 6 - Minimum Iteration: "
<< tree6.getMinIter() << endl;
// TestCase 7
NAryTree tree7(14);
tree7.addChild(0, 1);
tree7.addChild(0, 2);
tree7.addChild(0, 3);
tree7.addChild(1, 4);
tree7.addChild(2, 5);
tree7.addChild(2, 6);
tree7.addChild(4, 7);
tree7.addChild(5, 8);
tree7.addChild(5, 9);
tree7.addChild(7, 10);
tree7.addChild(8, 11);
tree7.addChild(8, 12);
tree7.addChild(10, 13);
cout << "TestCase 7 - Minimum Iteration: "
<< tree7.getMinIter() << endl;
// TestCase 8
NAryTree tree8(14);
tree8.addChild(0, 1);
tree8.addChild(0, 2);
tree8.addChild(0, 3);
tree8.addChild(0, 4);
tree8.addChild(0, 5);
tree8.addChild(1, 6);
tree8.addChild(2, 7);
tree8.addChild(3, 8);
tree8.addChild(4, 9);
tree8.addChild(6, 10);
tree8.addChild(7, 11);
tree8.addChild(8, 12);
tree8.addChild(9, 13);
cout << "TestCase 8 - Minimum Iteration: "
<< tree8.getMinIter() << endl;
// TestCase 9
NAryTree tree9(25);
tree9.addChild(0, 1);
tree9.addChild(0, 2);
tree9.addChild(0, 3);
tree9.addChild(0, 4);
tree9.addChild(0, 5);
tree9.addChild(0, 6);
tree9.addChild(1, 7);
tree9.addChild(2, 8);
tree9.addChild(3, 9);
tree9.addChild(4, 10);
tree9.addChild(5, 11);
tree9.addChild(6, 12);
tree9.addChild(7, 13);
tree9.addChild(8, 14);
tree9.addChild(9, 15);
tree9.addChild(10, 16);
tree9.addChild(11, 17);
tree9.addChild(12, 18);
tree9.addChild(13, 19);
tree9.addChild(14, 20);
tree9.addChild(15, 21);
tree9.addChild(16, 22);
tree9.addChild(17, 23);
tree9.addChild(19, 24);
cout << "TestCase 9 - Minimum Iteration: "
<< tree9.getMinIter() << endl;
return 0;
}
Java
// Java program to find minimum number of
// iterations to pass information from
// root to all nodes in an n-ary tree
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
class GFG
{
// No. of nodes
private static int N;
// Adjacency list containing
// list of children
private static List<List<Integer>> adj;
GFG(int N)
{
this.N = N;
adj = new ArrayList<>(N);
for (int i = 0; i < N; i++)
adj.add(new ArrayList<>());
}
// function to add a child w to v
void addChild(int v, int w)
{
adj.get(v).add(w);
}
// Main function to find the
// minimum iterations
private int getMinIteration()
{
// Base case : if height = 0 or 1;
if (N == 0 || N == 1)
return 0;
int[] mintItr = new int[N];
// Start Post Order Traversal from Root
getMinIterUtil(0, mintItr);
return mintItr[0];
}
/* A recursive function to used by getMinIter().
This function mainly does postorder traversal
and get minimum iteration of all children
of parent node, sort them in decreasing order
and then get minimum iteration of parent node
1. Get minItr(B) of all children (B) of a node (A)
2. Sort all minItr(B) in descending order
3. Get minItr of A based on all minItr(B)
minItr(A) = child(A) -->> child(A)
is children count of node A
For children B from i = 0 to child(A)
minItr(A) = max (minItr(A),
minItr(B) + i + 1)
Base cases would be:
If node is leaf, minItr = 0
If node's height is 1, minItr = children count
*/
private void getMinIterUtil(int u, int[] minItr)
{
// Base case : Leaf node
if (adj.get(u).size() == 0)
return;
minItr[u] = adj.get(u).size();
Integer[] minItrTemp = new Integer[minItr[u]];
int k = 0;
Iterator itr = adj.get(u).iterator();
while (itr.hasNext())
{
int currentChild = (int) itr.next();
getMinIterUtil(currentChild, minItr);
minItrTemp[k++] = minItr[currentChild];
}
Arrays.sort(minItrTemp, Collections.reverseOrder());
for (k = 0; k < adj.get(u).size(); k++)
{
int temp = minItrTemp[k] + k + 1;
minItr[u] = Math.max(minItr[u], temp);
}
}
// Driver Code
public static void main(String args[])
{
// TestCase1
GFG testCase1 = new GFG(17);
testCase1.addChild(0, 1);
testCase1.addChild(0, 2);
testCase1.addChild(0, 3);
testCase1.addChild(0, 4);
testCase1.addChild(0, 5);
testCase1.addChild(0, 6);
testCase1.addChild(1, 7);
testCase1.addChild(1, 8);
testCase1.addChild(1, 9);
testCase1.addChild(4, 10);
testCase1.addChild(4, 11);
testCase1.addChild(6, 12);
testCase1.addChild(7, 13);
testCase1.addChild(7, 14);
testCase1.addChild(10, 15);
testCase1.addChild(11, 16);
System.out.println("TestCase 1 - Minimum Iteration: " +
testCase1.getMinIteration());
// TestCase2
GFG testCase2 = new GFG(3);
testCase2.addChild(0, 1);
testCase2.addChild(0, 2);
System.out.println("TestCase 2 - Minimum Iteration: " +
testCase2.getMinIteration());
// TestCase3
GFG testCase3 = new GFG(1);
System.out.println("TestCase 3 - Minimum Iteration: " +
testCase3.getMinIteration());
// TestCase4
GFG testCase4 = new GFG(6);
testCase4.addChild(0, 1);
testCase4.addChild(1, 2);
testCase4.addChild(2, 3);
testCase4.addChild(3, 4);
testCase4.addChild(4, 5);
System.out.println("TestCase 4 - Minimum Iteration: " +
testCase4.getMinIteration());
// TestCase 5
GFG testCase5 = new GFG(6);
testCase5.addChild(0, 1);
testCase5.addChild(0, 2);
testCase5.addChild(2, 3);
testCase5.addChild(2, 4);
testCase5.addChild(2, 5);
System.out.println("TestCase 5 - Minimum Iteration: " +
testCase5.getMinIteration());
// TestCase 6
GFG testCase6 = new GFG(6);
testCase6.addChild(0, 1);
testCase6.addChild(0, 2);
testCase6.addChild(2, 3);
testCase6.addChild(2, 4);
testCase6.addChild(3, 5);
System.out.println("TestCase 6 - Minimum Iteration: " +
testCase6.getMinIteration());
// TestCase 7
GFG testCase7 = new GFG(14);
testCase7.addChild(0, 1);
testCase7.addChild(0, 2);
testCase7.addChild(0, 3);
testCase7.addChild(1, 4);
testCase7.addChild(2, 5);
testCase7.addChild(2, 6);
testCase7.addChild(4, 7);
testCase7.addChild(5, 8);
testCase7.addChild(5, 9);
testCase7.addChild(7, 10);
testCase7.addChild(8, 11);
testCase7.addChild(8, 12);
testCase7.addChild(10, 13);
System.out.println("TestCase 7 - Minimum Iteration: " +
testCase7.getMinIteration());
// TestCase 8
GFG testCase8 = new GFG(14);
testCase8.addChild(0, 1);
testCase8.addChild(0, 2);
testCase8.addChild(0, 3);
testCase8.addChild(0, 4);
testCase8.addChild(0, 5);
testCase8.addChild(1, 6);
testCase8.addChild(2, 7);
testCase8.addChild(3, 8);
testCase8.addChild(4, 9);
testCase8.addChild(6, 10);
testCase8.addChild(7, 11);
testCase8.addChild(8, 12);
testCase8.addChild(9, 13);
System.out.println("TestCase 8 - Minimum Iteration: " +
testCase8.getMinIteration());
// TestCase 9
GFG testCase9 = new GFG(25);
testCase9.addChild(0, 1);
testCase9.addChild(0, 2);
testCase9.addChild(0, 3);
testCase9.addChild(0, 4);
testCase9.addChild(0, 5);
testCase9.addChild(0, 6);
testCase9.addChild(1, 7);
testCase9.addChild(2, 8);
testCase9.addChild(3, 9);
testCase9.addChild(4, 10);
testCase9.addChild(5, 11);
testCase9.addChild(6, 12);
testCase9.addChild(7, 13);
testCase9.addChild(8, 14);
testCase9.addChild(9, 15);
testCase9.addChild(10, 16);
testCase9.addChild(11, 17);
testCase9.addChild(12, 18);
testCase9.addChild(13, 19);
testCase9.addChild(14, 20);
testCase9.addChild(15, 21);
testCase9.addChild(16, 22);
testCase9.addChild(17, 23);
testCase9.addChild(19, 24);
System.out.println("TestCase 9 - Minimum Iteration: " +
testCase9.getMinIteration());
}
}
// This code is contributed
// by MitaliSrivastava
Python3
# Python program to find minimum number of iterations to pass
# information from root to all nodes in an n-ary tree
from typing import List
# A class to represent n-ary tree (Note that the implementation
# is similar to graph for simplicity of implementation
class NAryTree:
def __init__(self, N: int):
# No. of nodes in a tree
self.N = N
# Pointer to an array containing list of children
self.adj = [[] for _ in range(N)]
# function to add a child w to v
def addChild(self, v: int, w: int):
self.adj[v].append(w)
# The main function to find minimum iterations
def getMinIter(self) -> int:
minItr = [0] * self.N
# A function used by getMinIter(), it basically does postorder
''' A recursive function to used by getMinIter(). This function
# mainly does postorder traversal and get minimum iteration of all children
# of node u, sort them in decreasing order and then get minimum iteration
# of node u
1. Get minItr(B) of all children (B) of a node (A)
2. Sort all minItr(B) in descending order
3. Get minItr of A based on all minItr(B)
minItr(A) = child(A) -->> child(A) is children count of node A
For children B from i = 0 to child(A)
minItr(A) = max ( minItr(A), minItr(B) + i + 1)
Base cases would be:
If node is leaf, minItr = 0
If node's height is 1, minItr = children count
'''
def getMinIterUtil(u: int) -> int:
nonlocal minItr
minItr[u] = len(self.adj[u])
minItrTemp = []
for i in self.adj[u]:
getMinIterUtil(i)
minItrTemp.append(minItr[i])
minItrTemp.sort(reverse=True)
for k in range(len(self.adj[u])):
tmp = minItrTemp[k] + k + 1
minItr[u] = max(minItr[u], tmp)
return minItr[u]
return getMinIterUtil(0)
# Drive Code
# Test Cases
# TestCase 1
tree1 = NAryTree(17)
tree1.addChild(0, 1)
tree1.addChild(0, 2)
tree1.addChild(0, 3)
tree1.addChild(0, 4)
tree1.addChild(0, 5)
tree1.addChild(0, 6)
tree1.addChild(1, 7)
tree1.addChild(1, 8)
tree1.addChild(1, 9)
tree1.addChild(4, 10)
tree1.addChild(4, 11)
tree1.addChild(6, 12)
tree1.addChild(7, 13)
tree1.addChild(7, 14)
tree1.addChild(10, 15)
tree1.addChild(11, 16)
print("TestCase 1 - Minimum Iteration:", tree1.getMinIter())
# TestCase 2
tree2 = NAryTree(3)
tree2.addChild(0, 1)
tree2.addChild(0, 2)
print("TestCase 2 - Minimum Iteration:", tree2.getMinIter())
# TestCase 3
tree3 = NAryTree(1)
print("TestCase 3 - Minimum Iteration:", tree3.getMinIter())
# TestCase 4
tree4 = NAryTree(6)
tree4.addChild(0, 1)
tree4.addChild(1, 2)
tree4.addChild(2, 3)
tree4.addChild(3, 4)
tree4.addChild(4, 5)
print("TestCase 4 - Minimum Iteration:", tree4.getMinIter())
# TestCase 5
tree5 = NAryTree(6)
tree5.addChild(0, 1)
tree5.addChild(0, 2)
tree5.addChild(2, 3)
tree5.addChild(2, 4)
tree5.addChild(2, 5)
print("TestCase 5 - Minimum Iteration:", tree5.getMinIter())
# TestCase 6
tree6 = NAryTree(6)
tree6.addChild(0, 1)
tree6.addChild(0, 2)
tree6.addChild(2, 3)
tree6.addChild(2, 4)
tree6.addChild(3, 5)
print("TestCase 6 - Minimum Iteration:",tree6.getMinIter())
# TestCase 7
tree7 = NAryTree(14)
tree7.addChild(0, 1)
tree7.addChild(0, 2)
tree7.addChild(0, 3)
tree7.addChild(1, 4)
tree7.addChild(2, 5)
tree7.addChild(2, 6)
tree7.addChild(4, 7)
tree7.addChild(5, 8)
tree7.addChild(5, 9)
tree7.addChild(7, 10)
tree7.addChild(8, 11)
tree7.addChild(8, 12)
tree7.addChild(10, 13)
print("TestCase 7 - Minimum Iteration:",tree7.getMinIter())
# TestCase 8
tree8 = NAryTree(14)
tree8.addChild(0, 1)
tree8.addChild(0, 2)
tree8.addChild(0, 3)
tree8.addChild(0, 4)
tree8.addChild(0, 5)
tree8.addChild(1, 6)
tree8.addChild(2, 7)
tree8.addChild(3, 8)
tree8.addChild(4, 9)
tree8.addChild(6, 10)
tree8.addChild(7, 11)
tree8.addChild(8, 12)
tree8.addChild(9, 13)
print("TestCase 8 - Minimum Iteration:",tree8.getMinIter())
# TestCase 9
tree9 = NAryTree(25)
tree9.addChild(0, 1)
tree9.addChild(0, 2)
tree9.addChild(0, 3)
tree9.addChild(0, 4)
tree9.addChild(0, 5)
tree9.addChild(0, 6)
tree9.addChild(1, 7)
tree9.addChild(2, 8)
tree9.addChild(3, 9)
tree9.addChild(4, 10)
tree9.addChild(5, 11)
tree9.addChild(6, 12)
tree9.addChild(7, 13)
tree9.addChild(8, 14)
tree9.addChild(9, 15)
tree9.addChild(10, 16)
tree9.addChild(11, 17)
tree9.addChild(12, 18)
tree9.addChild(13, 19)
tree9.addChild(14, 20)
tree9.addChild(15, 21)
tree9.addChild(16, 22)
tree9.addChild(17, 23)
tree9.addChild(19, 24)
print("TestCase 9 - Minimum Iteration:",tree9.getMinIter())
# This code is contributed by codebraxnzt
C#
// C# program to find minimum number of
// iterations to pass information from
// root to all nodes in an n-ary tree
using System;
using System.Collections.Generic;
class GFG
{
// No. of nodes
public int N;
// Adjacency list containing
// list of children
static List<List<int>> adj;
public GFG(int N)
{
this.N = N;
adj = new List<List<int>>(N);
for (int i = 0; i < N; i++)
adj.Add(new List<int>());
}
// function to add a child w to v
void addChild(int v, int w)
{
adj[v].Add(w);
}
// Main function to find the
// minimum iterations
private int getMinIteration()
{
// Base case : if height = 0 or 1;
if (N == 0 || N == 1)
return 0;
int[] mintItr = new int[N];
// Start Post Order Traversal from Root
getMinIterUtil(0, mintItr);
return mintItr[0];
}
/* A recursive function to used by getMinIter().
This function mainly does postorder traversal
and get minimum iteration of all children
of parent node, sort them in decreasing order
and then get minimum iteration of parent node
1. Get minItr(B) of all children (B) of a node (A)
2. Sort all minItr(B) in descending order
3. Get minItr of A based on all minItr(B)
minItr(A) = child(A) -->> child(A)
is children count of node A
For children B from i = 0 to child(A)
minItr(A) = max (minItr(A),
minItr(B) + i + 1)
Base cases would be:
If node is leaf, minItr = 0
If node's height is 1, minItr = children count
*/
private void getMinIterUtil(int u, int[] minItr)
{
// Base case : Leaf node
if (adj[u].Count == 0)
return;
minItr[u] = adj[u].Count;
int[] minItrTemp = new int[minItr[u]];
int k = 0;
// Iterator itr = adj.get(u).iterator();
foreach (int itr in adj[u])
{
int currentChild = (int) itr;
getMinIterUtil(currentChild, minItr);
minItrTemp[k++] = minItr[currentChild];
}
Array.Sort(minItrTemp);
for(int i =0, j = minItrTemp.Length-1; i<j;i++,j--){
int temp = minItrTemp[i];
minItrTemp[i] = minItrTemp[j];
minItrTemp[j] = temp;
}
for (k = 0; k < adj[u].Count; k++)
{
int temp = minItrTemp[k] + k + 1;
minItr[u] = Math.Max(minItr[u], temp);
}
}
// Driver Code
public static void Main(String []args)
{
// TestCase1
GFG testCase1 = new GFG(17);
testCase1.addChild(0, 1);
testCase1.addChild(0, 2);
testCase1.addChild(0, 3);
testCase1.addChild(0, 4);
testCase1.addChild(0, 5);
testCase1.addChild(0, 6);
testCase1.addChild(1, 7);
testCase1.addChild(1, 8);
testCase1.addChild(1, 9);
testCase1.addChild(4, 10);
testCase1.addChild(4, 11);
testCase1.addChild(6, 12);
testCase1.addChild(7, 13);
testCase1.addChild(7, 14);
testCase1.addChild(10, 15);
testCase1.addChild(11, 16);
Console.WriteLine("TestCase 1 - Minimum Iteration: " +
testCase1.getMinIteration());
// TestCase2
GFG testCase2 = new GFG(3);
testCase2.addChild(0, 1);
testCase2.addChild(0, 2);
Console.WriteLine("TestCase 2 - Minimum Iteration: " +
testCase2.getMinIteration());
// TestCase3
GFG testCase3 = new GFG(1);
Console.WriteLine("TestCase 3 - Minimum Iteration: " +
testCase3.getMinIteration());
// TestCase4
GFG testCase4 = new GFG(6);
testCase4.addChild(0, 1);
testCase4.addChild(1, 2);
testCase4.addChild(2, 3);
testCase4.addChild(3, 4);
testCase4.addChild(4, 5);
Console.WriteLine("TestCase 4 - Minimum Iteration: " +
testCase4.getMinIteration());
// TestCase 5
GFG testCase5 = new GFG(6);
testCase5.addChild(0, 1);
testCase5.addChild(0, 2);
testCase5.addChild(2, 3);
testCase5.addChild(2, 4);
testCase5.addChild(2, 5);
Console.WriteLine("TestCase 5 - Minimum Iteration: " +
testCase5.getMinIteration());
// TestCase 6
GFG testCase6 = new GFG(6);
testCase6.addChild(0, 1);
testCase6.addChild(0, 2);
testCase6.addChild(2, 3);
testCase6.addChild(2, 4);
testCase6.addChild(3, 5);
Console.WriteLine("TestCase 6 - Minimum Iteration: " +
testCase6.getMinIteration());
// TestCase 7
GFG testCase7 = new GFG(14);
testCase7.addChild(0, 1);
testCase7.addChild(0, 2);
testCase7.addChild(0, 3);
testCase7.addChild(1, 4);
testCase7.addChild(2, 5);
testCase7.addChild(2, 6);
testCase7.addChild(4, 7);
testCase7.addChild(5, 8);
testCase7.addChild(5, 9);
testCase7.addChild(7, 10);
testCase7.addChild(8, 11);
testCase7.addChild(8, 12);
testCase7.addChild(10, 13);
Console.WriteLine("TestCase 7 - Minimum Iteration: " +
testCase7.getMinIteration());
// TestCase 8
GFG testCase8 = new GFG(14);
testCase8.addChild(0, 1);
testCase8.addChild(0, 2);
testCase8.addChild(0, 3);
testCase8.addChild(0, 4);
testCase8.addChild(0, 5);
testCase8.addChild(1, 6);
testCase8.addChild(2, 7);
testCase8.addChild(3, 8);
testCase8.addChild(4, 9);
testCase8.addChild(6, 10);
testCase8.addChild(7, 11);
testCase8.addChild(8, 12);
testCase8.addChild(9, 13);
Console.WriteLine("TestCase 8 - Minimum Iteration: " +
testCase8.getMinIteration());
// TestCase 9
GFG testCase9 = new GFG(25);
testCase9.addChild(0, 1);
testCase9.addChild(0, 2);
testCase9.addChild(0, 3);
testCase9.addChild(0, 4);
testCase9.addChild(0, 5);
testCase9.addChild(0, 6);
testCase9.addChild(1, 7);
testCase9.addChild(2, 8);
testCase9.addChild(3, 9);
testCase9.addChild(4, 10);
testCase9.addChild(5, 11);
testCase9.addChild(6, 12);
testCase9.addChild(7, 13);
testCase9.addChild(8, 14);
testCase9.addChild(9, 15);
testCase9.addChild(10, 16);
testCase9.addChild(11, 17);
testCase9.addChild(12, 18);
testCase9.addChild(13, 19);
testCase9.addChild(14, 20);
testCase9.addChild(15, 21);
testCase9.addChild(16, 22);
testCase9.addChild(17, 23);
testCase9.addChild(19, 24);
Console.WriteLine("TestCase 9 - Minimum Iteration: " +
testCase9.getMinIteration());
}
}
// This code is contributed by aashish1995
JavaScript
<script>
var height;
var graph;
function findHeight(node , h)
{
height[node] = h;
for(let i=0;i<graph[node].length;i++)
{
let v = graph[node][i];
findHeight(v , h + 1);
}
}
function getMinIteration()
{
findHeight(0 , 0);
let max_height = 0;
for(let i=0;i<height.length;i++)
{
if(height[i] > max_height)
{
max_height = height[i];
}
}
for(let i=0;i<height.length;i++)
{
height[i] = max_height - height[i];
}
return getMinIterationUtil(0);
}
function getMinIterationUtil(node)
{
if(height[node] == 0 )
{
return 0;
}
if(height[node] == 1 )
{
return graph[node].length;
}
let edges =[...graph[node] ];
let edgeLenArr = [];
for(let i=0;i<edges.length;i++ )
{
edgeLenArr.push( graph[ graph[node][i] ].length );
}
for (let i = 0; i < edgeLenArr.length - 1; i++) {
for (let j = i + 1; j < edgeLenArr.length; j++) {
if(edgeLenArr[i] < edgeLenArr[j])
{
let temp = edgeLenArr[i];
edgeLenArr[i] = edgeLenArr[j];
edgeLenArr[j] = temp;
let temp1 = edges[i];
edges[i] = edges[j];
edges[j] = temp1;
}
}
}
let max_data = edges.length;
for(let i=0;i<edges.length;i++)
{
max_data = Math.max( max_data , i + 1 + getMinIterationUtil(edges[i]));
}
return max_data;
}
function addChild(a , b)
{
graph[a].push(b);
}
function intializeGraph(n)
{
height = new Array(n);
height.fill(0);
graph = new Array(n);
for(let i=0;i<graph.length;i++)
{ graph[i] = []; }
}
// TestCase1
intializeGraph(17);
addChild(0, 1);
addChild(0, 2);
addChild(0, 3);
addChild(0, 4);
addChild(0, 5);
addChild(0, 6);
addChild(1, 7);
addChild(1, 8);
addChild(1, 9);
addChild(4, 10);
addChild(4, 11);
addChild(6, 12);
addChild(7, 13);
addChild(7, 14);
addChild(10, 15);
addChild(11, 16);
document.write("TestCase 1 - Minimum Iteration: " + getMinIteration());
document.write('<br>');
document.write('<br>');
// TestCase2
intializeGraph(3);
addChild(0, 1);
addChild(0, 2);
document.write("TestCase 2 - Minimum Iteration: " + getMinIteration());
document.write('<br>');
document.write('<br>');
// TestCase3
intializeGraph(1);
document.write("TestCase 3 - Minimum Iteration: " + getMinIteration(1));
document.write('<br>');
document.write('<br>');
// // TestCase4
intializeGraph(6);
addChild(0, 1);
addChild(1, 2);
addChild(2, 3);
addChild(3, 4);
addChild(4, 5);
document.write("TestCase 4 - Minimum Iteration: " + getMinIteration());
document.write('<br>');
document.write('<br>');
// TestCase 5
intializeGraph(6);
addChild(0, 1);
addChild(0, 2);
addChild(2, 3);
addChild(2, 4);
addChild(2, 5);
document.write("TestCase 5 - Minimum Iteration: " + getMinIteration());
document.write('<br>');
document.write('<br>');
// TestCase 6
intializeGraph(6);
addChild(0, 1);
addChild(0, 2);
addChild(2, 3);
addChild(2, 4);
addChild(3, 5);
document.write("TestCase 6 - Minimum Iteration: " + getMinIteration());
document.write('<br>');
document.write('<br>');
// TestCase 7
intializeGraph(14);
addChild(0, 1);
addChild(0, 2);
addChild(0, 3);
addChild(1, 4);
addChild(2, 5);
addChild(2, 6);
addChild(4, 7);
addChild(5, 8);
addChild(5, 9);
addChild(7, 10);
addChild(8, 11);
addChild(8, 12);
addChild(10, 13);
document.write("TestCase 7 - Minimum Iteration: " + getMinIteration());
document.write('<br>');
document.write('<br>');
// TestCase 8
intializeGraph(14);
addChild(0, 1);
addChild(0, 2);
addChild(0, 3);
addChild(0, 4);
addChild(0, 5);
addChild(1, 6);
addChild(2, 7);
addChild(3, 8);
addChild(4, 9);
addChild(6, 10);
addChild(7, 11);
addChild(8, 12);
addChild(9, 13);
document.write("TestCase 8 - Minimum Iteration: " + getMinIteration());
document.write('<br>');
document.write('<br>');
// TestCase 9
intializeGraph(25);
addChild(0, 1);
addChild(0, 2);
addChild(0, 3);
addChild(0, 4);
addChild(0, 5);
addChild(0, 6);
addChild(1, 7);
addChild(2, 8);
addChild(3, 9);
addChild(4, 10);
addChild(5, 11);
addChild(6, 12);
addChild(7, 13);
addChild(8, 14);
addChild(9, 15);
addChild(10, 16);
addChild(11, 17);
addChild(12, 18);
addChild(13, 19);
addChild(14, 20);
addChild(15, 21);
addChild(16, 22);
addChild(17, 23);
addChild(19, 24);
document.write("TestCase 9 - Minimum Iteration: " + getMinIteration(25));
document.write('<br>');
document.write('<br>');
//this code is contributed by gaurav2146
</script>
OutputTestCase 1 - Minimum Iteration: 6
TestCase 2 - Minimum Iteration: 2
TestCase 3 - Minimum Iteration: 0
TestCase 4 - Minimum Iteration: 5
TestCase 5 - Minimum Iteration: 4
TestCase 6 - Minimum Iteration: 3
TestCase 7 - Minimum Iteration: 6
TestCase 8 - Minimum Iteration: 6
TestCase 9 - Minimum Iteration: 8
Similar Reads
Minimum time required to infect all the nodes of Binary tree
Given a binary tree and a node start that is initially infected. For every second, neighbours of an infected node get infected. The task is to find the minimum time in which the whole tree will be infected. Examples: Input: 10 / \ 12 13 / \ 14 15 / \ / \21 22 23 24Start = 14Output: 3 Input: 3 / \ 4
15+ min read
Maximize sum of path from the Root to a Leaf node in N-ary Tree
Given a generic tree consisting of n nodes, the task is to find the maximum sum of the path from the root to the leaf node.Examples:Input:Output: 12Explanation: The path sum to every leaf from the root are:For node 4: 1 -> 2 -> 4 = 7For node 5: 1 -> 2 -> 5 = 8For node 6: 1 -> 3 ->
5 min read
Minimum number of cameras required to monitor all nodes of a Binary Tree
Given a Binary Tree consisting of N nodes, the task is to find the minimum number of cameras required to monitor the entire tree such that every camera placed at any node can monitor the node itself, its parent, and its immediate children. Examples: Input: 0 / 0 /\ 0 0Output: 1Explanation: 0 / 0
8 min read
Find the path from root to the given nodes of a tree for multiple queries
Given a tree with N vertices numbered from 0 to N - 1 (0th node is the root node). Also, given q queries containing nodes in the tree. The task is to find the path from the root node to the given node for multiple queries. Examples: Input: N = 6, q[] = {2, 4} Tree: 0 / \ 1 2 | 3 / \ 4 5 Output: 0 2
10 min read
Maximum sum of leaf nodes among all levels of the given binary tree
Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum of leaf nodes among all level of the given binary tree.Examples: Input: 4 / \ 2 -5 / \ -1 3 Output: 2 Sum of all leaves at 0th level is 0. Sum of all leaves at 1st level is -5. Sum of all leaves at 2nd level
9 min read
Convert given Binary Tree to Symmetric Tree by adding minimum number of nodes
Given a Binary Tree, the task is to convert the given Binary Tree to the Symmetric Tree by adding the minimum number of nodes in the given Tree. Examples: Input: Output: Input: Output: Approach: To solve this problem, follow the below steps: Make a function buildSymmetricTree which will accept two p
8 min read
Minimum sum of a set of nodes of Tree following given conditions
Given a tree with N node and N-1 edges and an array arr[] where arr[i] denotes the value of ith node, the task is to find a set of nodes such that the sum of values is minimum and all the other nodes outside the set have an edge with at least one of the nodes in the set. Examples: Input: N = 3, edge
15+ min read
Minimum nodes to be removed to make a Binary tree complete
Given a binary tree with positive values of nodes, find the minimum number of nodes that need to be removed to transform it into a complete binary tree. Return 0 if the given tree is already complete. Note: A complete binary tree is a special type of binary tree where all the levels of the tree are
15+ min read
Minimum distance to visit all the nodes of an undirected weighted tree
Given a weighted tree with N nodes starting from 1 to N. The distance between any two nodes is given by the edge weight. Node 1 is the source, the task is to visit all the nodes of the tree with the minimum distance traveled. Examples: Input: u[] = {1, 1, 2, 2, 1} v[] = {2, 3, 5, 6, 4} w[] = {1, 4,
10 min read
Print path from a node to root of given Complete Binary Tree
Given an integer N, the task is to find the path from the Nth node to the root of a Binary Tree of the following form: The Binary Tree is a Complete Binary Tree up to the level of the Nth node.The nodes are numbered 1 to N, starting from the root as 1.The structure of the Tree is as follows: 1 / \ 2
4 min read