Given an N-ary tree consisting of N nodes numbered from 1 to N rooted at node 1, the task is to assign values to each node of the tree such that the sum of values from any root to the leaf path which contains at least two nodes is not divisible by the number of nodes along that path.
Examples:
Input: N = 11, edges[][] = {{1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 6}, {2, 10}, {10, 11}, {3, 7}, {4, 8}, {5, 9}}
Output: 1 2 1 2 2 1 1
Explanation:

According to the above assignment of values, below are all the possible paths from the root to leaf:
- Path 1 ? 2 ? 6, sum = 1 + 2 + 1 = 4, length = 3.
- Path 1 ? 2 ? 10 ? 11, sum = 1 + 2 + 1 + 2 = 6, length = 4
- Path 1 ? 3 ? 7, sum = 1 + 2 + 1 = 4, length = 3.
- Path 1 ? 4 ? 8, sum = 1 + 2 + 1 = 4, length = 3.
- Path 1 ? 5 ? 9, sum = 1 + 2 + 1 = 4, length = 3.
From all the above paths, none of the paths exists having the sum of values divisible by their length.
Input: N = 3, edges = {{1, 2}, {2, 3}}
Output: 1 2 1
Approach: The given problem can be solved based on the observation that for any root to leaf path with a number of nodes at least 2, say K if the sum of values along this path lies between K and 2*K exclusive, then that sum can never be divisible by K as any number over the range (K, 2*K) is never divisible by K. Therefore, for K = 1, assign node values of odd level nodes as 1, and rest as 2. Follow the steps below to solve the problem:
- Initialize an array, say answer[] of size N + 1 to store the values assigned to the nodes.
- Initialize a variable, say K as 1 to assign values to each node.
- Initialize a queue that is used to perform BFS Traversal on the given tree and push node with value 1 in the queue and initialize the value to the nodes as 1.
- Iterate until then the queue is non-empty and perform the following steps:
- Pop the front node of the queue and if the value assigned to the popped node is 1 then update the value of K to 2. Otherwise, update K as 1.
- Traverse all the child nodes of the current popped node and push the child node in the queue and assigned the value K to the child node.
- After completing the above steps, print the values stored in the array answer[] as the result.
Below is the implementation of the above approach:
C++
#include "bits/stdc++.h"
using namespace std;
void assignValues( int Edges[][2], int n)
{
vector < int > tree[n + 1];
for ( int i = 0; i < n - 1; i++) {
int u = Edges[i][0];
int v = Edges[i][1];
tree[u].push_back(v);
tree[v].push_back(u);
}
vector < bool > visited(n + 1, false );
vector < int > answer(n + 1);
int K = 1;
queue < int > q;
q.push(1);
answer[1] = K;
while (!q.empty()) {
int node = q.front();
q.pop();
visited[node] = true ;
K = ((answer[node] == 1) ? 2 : 1);
for ( auto child : tree[node]) {
if (!visited[child]) {
q.push(child);
answer[child] = K;
}
}
}
for ( int i = 1; i <= n; i++) {
cout << answer[i] << " " ;
}
}
int main()
{
int N = 11;
int Edges[][2] = {{1, 2}, {1, 3}, {1, 4},
{1, 5}, {2, 6}, {2, 10},
{10, 11}, {3, 7}, {4, 8},
{5, 9}};
assignValues(Edges, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void assignValues( int Edges[][], int n)
{
ArrayList<ArrayList<Integer>> tree = new ArrayList<>();
for ( int i = 0 ; i < n + 1 ; i++)
tree.add( new ArrayList<>());
for ( int i = 0 ; i < n - 1 ; i++)
{
int u = Edges[i][ 0 ];
int v = Edges[i][ 1 ];
tree.get(u).add(v);
tree.get(v).add(u);
}
boolean [] visited = new boolean [n + 1 ];
int [] answer = new int [n + 1 ];
int K = 1 ;
Queue<Integer> q = new LinkedList<>();
q.add( 1 );
answer[ 1 ] = K;
while (!q.isEmpty())
{
int node = q.peek();
q.poll();
visited[node] = true ;
K = ((answer[node] == 1 ) ? 2 : 1 );
for (Integer child : tree.get(node))
{
if (!visited[child])
{
q.add(child);
answer[child] = K;
}
}
}
for ( int i = 1 ; i <= n; i++)
{
System.out.print(answer[i] + " " );
}
}
public static void main(String[] args)
{
int N = 11 ;
int Edges[][] = { { 1 , 2 }, { 1 , 3 },
{ 1 , 4 }, { 1 , 5 },
{ 2 , 6 }, { 2 , 10 },
{ 10 , 11 }, { 3 , 7 },
{ 4 , 8 }, { 5 , 9 } };
assignValues(Edges, N);
}
}
|
Python3
from collections import deque
def assignValues(Edges, n):
tree = [[] for i in range (n + 1 )]
for i in range (n - 1 ):
u = Edges[i][ 0 ]
v = Edges[i][ 1 ]
tree[u].append(v)
tree[v].append(u)
visited = [ False ] * (n + 1 )
answer = [ 0 ] * (n + 1 )
K = 1
q = deque()
q.append( 1 )
answer[ 1 ] = K
while ( len (q) > 0 ):
node = q.popleft()
visited[node] = True
K = 2 if (answer[node] = = 1 ) else 1
for child in tree[node]:
if ( not visited[child]):
q.append(child)
answer[child] = K
for i in range ( 1 , n + 1 ):
print (answer[i],end = " " )
if __name__ = = '__main__' :
N = 7
Edges = [ [ 1 , 2 ], [ 4 , 6 ],
[ 3 , 5 ], [ 1 , 4 ],
[ 7 , 5 ], [ 5 , 1 ] ]
assignValues(Edges, N)
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
public class GFG{
static void assignValues( int [, ] Edges, int n)
{
LinkedList< int >[] tree = new LinkedList< int >[n+1];
for ( int i = 0; i < n + 1; i++)
tree[i] = new LinkedList< int >();
for ( int i = 0; i < n - 1; i++)
{
int u = Edges[i, 0];
int v = Edges[i, 1];
tree[u].AddLast(v);
tree[v].AddLast(u);
}
bool [] visited = new bool [n + 1];
int [] answer = new int [n + 1];
int K = 1;
Queue q = new Queue();
q.Enqueue(1);
answer[1] = K;
while (q.Count > 0)
{
int node = ( int )q.Peek();
q.Dequeue();
visited[node] = true ;
K = ((answer[node] == 1) ? 2 : 1);
foreach ( var child in tree[node])
{
if (!visited[child])
{
q.Enqueue(child);
answer[child] = K;
}
}
}
for ( int i = 1; i <= n; i++)
{
Console.Write(answer[i] + " " );
}
}
static public void Main (){
int N = 11;
int [, ] Edges = { { 1, 2 }, { 1, 3 },
{ 1, 4 }, { 1, 5 },
{ 2, 6 }, { 2, 10 },
{ 10, 11 }, { 3, 7 },
{ 4, 8 }, { 5, 9 } };
assignValues(Edges, N);
}
}
|
Javascript
<script>
function assignValues(Edges, n)
{
var tree = Array.from(Array(n+1), ()=> Array());
for ( var i = 0; i < n - 1; i++) {
var u = Edges[i][0];
var v = Edges[i][1];
tree[u].push(v);
tree[v].push(u);
}
var visited = Array(n + 1).fill( false );
var answer = Array(n + 1);
var K = 1;
var q = [];
q.push(1);
answer[1] = K;
while (q.length!=0) {
var node = q[0];
q.shift();
visited[node] = true ;
K = ((answer[node] == 1) ? 2 : 1);
tree[node].forEach(child => {
if (!visited[child]) {
q.push(child);
answer[child] = K;
}
});
}
for ( var i = 1; i <= n; i++) {
document.write( answer[i] + " " );
}
}
var N = 11;
var Edges = [[1, 2], [1, 3], [1, 4],
[1, 5], [2, 6], [2, 10],
[10, 11], [3, 7], [4, 8],
[5, 9]];
assignValues(Edges, N);
</script>
|
Output: 1 2 2 2 2 1 1 1 1 1 2
Time Complexity: O(N), where N is the total number of nodes in the tree.
Auxiliary Space: O(N)