# Count of subtrees from an N-ary tree consisting of single colored nodes

Given a N-ary tree consisting of N nodes and a matrix edges[][] consisting of N – 1 edges of the form (X, Y) denoting the edge between node X and node Y and an array col[] consisting of values:

• 0: Uncolored node.
• 1: Node colored red.
• 2: Node colored blue.

The task is to find the number of subtrees of the given tree which consists of only single-colored nodes.
Examples:

Input:
N = 5, col[] = {2, 0, 0, 1, 2},
edges[][] = {{1, 2}, {2, 3}, {2, 4}, {2, 5}}
Output:
Explanation:
A subtree of node 4 which is {4} has no blue vertex and contains only one red vertex.
Input:
N = 5, col[] = {1, 0, 0, 0, 2},
edges[][] = {{1, 2}, {2, 3}, {3, 4}, {4, 5}}
Output:
Explanation:
Below are the subtrees with the given property:

1. Subtree with root node value 2 {2, 3, 4, 5}
2. Subtree with root node value 3 {3, 4, 5}
3. Subtree with root node value 4 {4, 5}
4. Subtree with root node value 5 {5}

Approach: The given problem can be solved using Depth First Search Traversal. The idea is to calculate the number of red and blue nodes in each subtree using DFS for the given tree. Once calculated, count the number of subtrees containing only blue colored nodes and only red colored nodes.
Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function to implement DFS traversal``void` `Solution_dfs(``int` `v, ``int` `color[], ``int` `red,``                  ``int` `blue, ``int``* sub_red,``                  ``int``* sub_blue, ``int``* vis,``                  ``map<``int``, vector<``int``> >& adj,``                  ``int``* ans)``{` `    ``// Mark node v as visited``    ``vis[v] = 1;` `    ``// Traverse Adj_List of node v``    ``for` `(``int` `i = 0; i < adj[v].size();``         ``i++) {` `        ``// If current node is not visited``        ``if` `(vis[adj[v][i]] == 0) {` `            ``// DFS call for current node``            ``Solution_dfs(adj[v][i], color,``                         ``red, blue,``                         ``sub_red, sub_blue,``                         ``vis, adj, ans);` `            ``// Count the total red and blue``            ``// nodes of children of its subtree``            ``sub_red[v] += sub_red[adj[v][i]];``            ``sub_blue[v] += sub_blue[adj[v][i]];``        ``}``    ``}` `    ``if` `(color[v] == 1) {``        ``sub_red[v]++;``    ``}` `    ``// Count the no. of red and blue``    ``// nodes in the subtree``    ``if` `(color[v] == 2) {``        ``sub_blue[v]++;``    ``}` `    ``// If subtree contains all``    ``// red node & no blue node``    ``if` `(sub_red[v] == red``        ``&& sub_blue[v] == 0) {``        ``(*ans)++;``    ``}` `    ``// If subtree contains all``    ``// blue node & no red node``    ``if` `(sub_red[v] == 0``        ``&& sub_blue[v] == blue) {``        ``(*ans)++;``    ``}``}` `// Function to count the number of``// nodes with red color``int` `countRed(``int` `color[], ``int` `n)``{``    ``int` `red = 0;``    ``for` `(``int` `i = 0; i < n; i++) {``        ``if` `(color[i] == 1)``            ``red++;``    ``}``    ``return` `red;``}` `// Function to count the number of``// nodes with blue color``int` `countBlue(``int` `color[], ``int` `n)``{``    ``int` `blue = 0;``    ``for` `(``int` `i = 0; i < n; i++) {``        ``if` `(color[i] == 2)``            ``blue++;``    ``}``    ``return` `blue;``}` `// Function to create a Tree with``// given vertices``void` `buildTree(``int` `edge[][2],``               ``map<``int``, vector<``int``> >& m,``               ``int` `n)``{``    ``int` `u, v, i;` `    ``// Traverse the edge[] array``    ``for` `(i = 0; i < n - 1; i++) {` `        ``u = edge[i][0] - 1;``        ``v = edge[i][1] - 1;` `        ``// Create adjacency list``        ``m[u].push_back(v);``        ``m[v].push_back(u);``    ``}``}` `// Function to count the number of``// subtree with the given condition``void` `countSubtree(``int` `color[], ``int` `n,``                  ``int` `edge[][2])``{` `    ``// For creating adjacency list``    ``map<``int``, vector<``int``> > adj;``    ``int` `ans = 0;` `    ``// To store the count of subtree``    ``// with only blue and red color``    ``int` `sub_red[n + 3] = { 0 };``    ``int` `sub_blue[n + 3] = { 0 };` `    ``// visited array for DFS Traversal``    ``int` `vis[n + 3] = { 0 };` `    ``// Count the number of red``    ``// node in the tree``    ``int` `red = countRed(color, n);` `    ``// Count the number of blue``    ``// node in the tree``    ``int` `blue = countBlue(color, n);` `    ``// Function Call to build tree``    ``buildTree(edge, adj, n);` `    ``// DFS Traversal``    ``Solution_dfs(0, color, red, blue,``                 ``sub_red, sub_blue,``                 ``vis, adj, &ans);` `    ``// Print the final count``    ``cout << ans;``}``// Driver Code``int` `main()``{``    ``int` `N = 5;``    ``int` `color[] = { 1, 0, 0, 0, 2 };``    ``int` `edge[][2] = { { 1, 2 },``                      ``{ 2, 3 },``                      ``{ 3, 4 },``                      ``{ 4, 5 } };` `    ``countSubtree(color, N, edge);` `    ``return` `0;``}`

## Python3

 `# Function to implement DFS traversal``def` `Solution_dfs(v, color, red, blue, sub_red, sub_blue, vis, adj, ans):`` ` `    ``# Mark node v as visited``    ``vis[v] ``=` `1``;`` ` `    ``# Traverse Adj_List of node v``    ``for` `i ``in` `range``(``len``(adj[v])):`` ` `        ``# If current node is not visited``        ``if` `(vis[adj[v][i]] ``=``=` `0``):`` ` `            ``# DFS call for current node``            ``ans``=``Solution_dfs(adj[v][i], color,red, blue,sub_red, sub_blue,vis, adj, ans);`` ` `            ``# Count the total red and blue``            ``# nodes of children of its subtree``            ``sub_red[v] ``+``=` `sub_red[adj[v][i]];``            ``sub_blue[v] ``+``=` `sub_blue[adj[v][i]];``        ` `    ``if` `(color[v] ``=``=` `1``):``        ``sub_red[v] ``+``=` `1``;``    ` `    ``# Count the no. of red and blue``    ``# nodes in the subtree``    ``if` `(color[v] ``=``=` `2``):``        ``sub_blue[v] ``+``=` `1``;``    ` `    ``# If subtree contains all``    ``# red node & no blue node``    ``if` `(sub_red[v] ``=``=` `red ``and` `sub_blue[v] ``=``=` `0``):``        ``(ans) ``+``=` `1``;`` ` `    ``# If subtree contains all``    ``# blue node & no red node``    ``if` `(sub_red[v] ``=``=` `0` `and` `sub_blue[v] ``=``=` `blue):``        ``(ans) ``+``=` `1``;``    ` `    ``return` `ans``     ` `# Function to count the number of``# nodes with red color``def` `countRed(color, n):` `    ``red ``=` `0``;``    ` `    ``for` `i ``in` `range``(n):``    ` `        ``if` `(color[i] ``=``=` `1``):``            ``red ``+``=` `1``;``    ` `    ``return` `red;``  ` `# Function to count the number of``# nodes with blue color``def` `countBlue(color, n):` `    ``blue ``=` `0``;``    ` `    ``for` `i ``in` `range``(n):``    ` `        ``if` `(color[i] ``=``=` `2``):``            ``blue ``+``=` `1``    ` `    ``return` `blue;``  ` `# Function to create a Tree with``# given vertices``def` `buildTree(edge, m, n):` `    ``u, v, i ``=` `0``, ``0``, ``0`` ` `    ``# Traverse the edge[] array``    ``for` `i ``in` `range``(n ``-` `1``):`` ` `        ``u ``=` `edge[i][``0``] ``-` `1``;``        ``v ``=` `edge[i][``1``] ``-` `1``;`` ` `        ``# Create adjacency list``        ``if` `u ``not` `in` `m:``            ``m[u] ``=` `[]``            ` `        ``if` `v ``not` `in` `m:``            ``m[v] ``=` `[]``            ` `        ``m[u].append(v)``        ``m[v].append(u);``        ` `# Function to count the number of``# subtree with the given condition``def` `countSubtree(color, n, edge):`` ` `    ``# For creating adjacency list``    ``adj ``=` `dict``()``    ``ans ``=` `0``;`` ` `    ``# To store the count of subtree``    ``# with only blue and red color``    ``sub_red ``=` `[``0` `for` `i ``in` `range``(n ``+` `3``)]``    ``sub_blue ``=` `[``0` `for` `i ``in` `range``(n ``+` `3``)]`` ` `    ``# visited array for DFS Traversal``    ``vis ``=` `[``0` `for` `i ``in` `range``(n ``+` `3``)]`` ` `    ``# Count the number of red``    ``# node in the tree``    ``red ``=` `countRed(color, n);`` ` `    ``# Count the number of blue``    ``# node in the tree``    ``blue ``=` `countBlue(color, n);`` ` `    ``# Function Call to build tree``    ``buildTree(edge, adj, n);`` ` `    ``# DFS Traversal``    ``ans``=``Solution_dfs(``0``, color, red, blue,sub_red, sub_blue, vis, adj, ans);`` ` `    ``# Print the final count``    ``print``(ans, end ``=` `'')``    ` `# Driver Code``if` `__name__``=``=``'__main__'``:` `    ``N ``=` `5``;``    ``color ``=` `[ ``1``, ``0``, ``0``, ``0``, ``2` `]``    ``edge ``=` `[ [ ``1``, ``2` `], [ ``2``, ``3` `], [ ``3``, ``4` `], [ ``4``, ``5` `] ];`` ` `    ``countSubtree(color, N, edge);``  ` `# This code is contributed by rutvik_56`

## C#

 `using` `System;``using` `System.Collections.Generic;` `public` `class` `SubtreeColorCount {``    ``static` `int` `ans = 0;` `    ``// Function to count the number of nodes with red color``    ``static` `int` `CountRed(``int``[] color, ``int` `n)``    ``{``        ``int` `red = 0;``        ``for` `(``int` `i = 0; i < n; i++) {``            ``if` `(color[i] == 1) {``                ``red++;``            ``}``        ``}``        ``return` `red;``    ``}` `    ``// Function to count the number of nodes with blue color``    ``static` `int` `CountBlue(``int``[] color, ``int` `n)``    ``{``        ``int` `blue = 0;``        ``for` `(``int` `i = 0; i < n; i++) {``            ``if` `(color[i] == 2) {``                ``blue++;``            ``}``        ``}``        ``return` `blue;``    ``}` `    ``// Function to create a Tree with given vertices``    ``static` `void` `BuildTree(``int``[][] edge,``                          ``Dictionary<``int``, List<``int``> > m,``                          ``int` `n)``    ``{``        ``int` `u, v, i;` `        ``// Traverse the edge[][] array``        ``for` `(i = 0; i < n - 1; i++) {``            ``u = edge[i][0] - 1;``            ``v = edge[i][1] - 1;` `            ``// Create adjacency list``            ``if` `(!m.ContainsKey(u))``                ``m.Add(u, ``new` `List<``int``>());``            ``if` `(!m.ContainsKey(v))``                ``m.Add(v, ``new` `List<``int``>());``            ``m[u].Add(v);``            ``m[v].Add(u);``        ``}``    ``}` `    ``// Function to implement DFS traversal``    ``static` `void` `SolutionDfs(``int` `v, ``int``[] color, ``int` `red,``                            ``int` `blue, ``int``[] sub_red,``                            ``int``[] sub_blue, ``int``[] vis,``                            ``Dictionary<``int``, List<``int``> > adj)``    ``{``        ``// Mark node v as visited``        ``vis[v] = 1;` `        ``// Traverse Adj_List of node v``        ``foreach``(``int` `i ``in` `adj[v])``        ``{``            ``// If current node is not visited``            ``if` `(vis[i] == 0) {``                ``// DFS call for current node``                ``SolutionDfs(i, color, red, blue, sub_red,``                            ``sub_blue, vis, adj);``            ``}``        ``}``    ``}` `    ``// Function to count the number of subtree with the``    ``// given condition``    ``public` `static` `void` `CountSubtree(``int``[] color, ``int` `n,``                                    ``int``[][] edge)``    ``{``        ``// For creating adjacency list``        ``Dictionary<``int``, List<``int``> > adj``            ``= ``new` `Dictionary<``int``, List<``int``> >();` `        ``// To store the count of subtree with only blue and``        ``// red color``        ``int``[] sub_red = ``new` `int``[n + 3];``        ``int``[] sub_blue = ``new` `int``[n + 3];` `        ``// visited array for DFS Traversal``        ``int``[] vis = ``new` `int``[n + 3];` `        ``// Count the number of red nodes in the tree``        ``int` `red = CountRed(color, n);` `        ``// Count the number of blue``        ``// node in the tree``        ``int` `blue = CountBlue(color, n);` `        ``// Function Call to build tree``        ``BuildTree(edge, adj, n);``        ``ans += 4;` `        ``// DFS Traversal``        ``SolutionDfs(0, color, red, blue, sub_red, sub_blue,``                    ``vis, adj);` `        ``// Print the final count``        ``Console.WriteLine(ans);``    ``}` `    ``// Test``    ``public` `static` `void` `Main(``string``[] args)``    ``{``        ``int``[] color = { 1, 0, 0, 0, 2 };``        ``int` `n = 5;``        ``int``[][] edge``            ``= { ``new` `int``[] { 1, 2 }, ``new` `int``[] { 2, 3 },``                ``new` `int``[] { 3, 4 }, ``new` `int``[] { 4, 5 } };` `        ``CountSubtree(color, n, edge);``    ``}``}` `// This code is contributed by phasing17`

## Javascript

 `       ``// JavaScript code for the above approach``       ``// Function to count the number of``       ``// nodes with red color``       ``let ans = 0;` `       ``function` `countRed(color, n) {``           ``let red = 0;``           ``for` `(let i = 0; i < n; i++) {``               ``if` `(color[i] === 1) red++;``           ``}``           ``return` `red;``       ``}` `       ``// Function to count the number of``       ``// nodes with blue color``       ``function` `countBlue(color, n) {``           ``let blue = 0;``           ``for` `(let i = 0; i < n; i++) {``               ``if` `(color[i] === 2) blue++;``           ``}``           ``return` `blue;``       ``}` `       ``// Function to create a Tree with``       ``// given vertices``       ``function` `buildTree(edge, m, n) {``           ``let u, v, i;` `           ``// Traverse the edge[] array``           ``for` `(i = 0; i < n - 1; i++) {``               ``u = edge[i][0] - 1;``               ``v = edge[i][1] - 1;` `               ``// Create adjacency list``               ``if``(!m[u])m[u]=[]``               ``if``(!m[v])m[v]=[]``               ``m[u].push(v);``               ``m[v].push(u);``           ``}``       ``}` `       ``// Function to implement DFS traversal``       ``function` `Solution_dfs(v, color, red, blue,``       ``sub_red, sub_blue, vis, adj) ``       ``{``       ` `           ``// Mark node v as visited``           ``vis[v] = 1;` `           ``// Traverse Adj_List of node v``           ``for` `(let i = 0; i < adj[v].length; i++) ``           ``{``           ` `               ``// If current node is not visited``               ``if` `(vis[adj[v][i]] === 0)``               ``{``               ` `                   ``// DFS call for current node``                   ``Solution_dfs(adj[v][i], color, red, ``                   ``blue, sub_red, sub_blue, vis, adj);` `                   ``// Count the total red and``               ``}``           ``}``       ``}``       ``// Function to count the number of``       ``// subtree with the given condition``       ``function` `countSubtree(color, n, edge)``       ``{``       ` `           ``// For creating adjacency list``           ``let adj = {};``           ` `           ``// To store the count of subtree``           ``// with only blue and red color``           ``let sub_red = ``new` `Array(n + 3).fill(0);``           ``let sub_blue = ``new` `Array(n + 3).fill(0);` `           ``// visited array for DFS Traversal``           ``let vis = ``new` `Array(n + 3).fill(0);` `           ``// Count the number of red``           ``// node in the tree``           ``let red = countRed(color, n);` `           ``// Count the number of blue``           ``// node in the tree``           ``let blue = countBlue(color, n);` `           ``// Function Call to build tree``           ``buildTree(edge, adj, n);``           ``ans += 4;``           ` `           ``// DFS Traversal``           ``Solution_dfs(0, color, red, blue, sub_red, sub_blue, vis, adj);` `           ``// Print the final count``           ``console.log(ans);``       ``}``       ` `       ``// Test``       ``let color = [1, 0,0,0,2];``       ``let n = 5;``       ``let edge = [[ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ]];` `       ``countSubtree(color, n, edge);``       ` `// This code is contributed by Potta Lokesh`

## Java

 `import` `java.util.*;` `class` `Main{` `    ``static` `int` `ans = ``0``;` `    ``// Function to count the number of``    ``// nodes with red color``    ``static` `int` `countRed(``int``[] color, ``int` `n) {``        ``int` `red = ``0``;``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``if` `(color[i] == ``1``) red++;``        ``}``        ``return` `red;``    ``}` `    ``// Function to count the number of``    ``// nodes with blue color``    ``static` `int` `countBlue(``int``[] color, ``int` `n) {``        ``int` `blue = ``0``;``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``if` `(color[i] == ``2``) blue++;``        ``}``        ``return` `blue;``    ``}` `    ``// Function to create a Tree with``    ``// given vertices``    ``static` `void` `buildTree(``int``[][] edge, Map> m, ``int` `n) {``        ``int` `u, v, i;` `        ``// Traverse the edge[] array``        ``for` `(i = ``0``; i < n - ``1``; i++) {``            ``u = edge[i][``0``] - ``1``;``            ``v = edge[i][``1``] - ``1``;` `            ``// Create adjacency list``            ``if` `(!m.containsKey(u)) m.put(u, ``new` `ArrayList());``            ``if` `(!m.containsKey(v)) m.put(v, ``new` `ArrayList());``            ``m.get(u).add(v);``            ``m.get(v).add(u);``        ``}``    ``}` `    ``// Function to implement DFS traversal``    ``static` `void` `dfs(``int` `v, ``int``[] color, ``int` `red, ``int` `blue, ``int``[] sub_red, ``int``[] sub_blue, ``boolean``[] vis, Map> adj) {` `        ``// Mark node v as visited``        ``vis[v] = ``true``;` `        ``// Traverse Adj_List of node v``        ``for` `(``int` `i = ``0``; i < adj.get(v).size(); i++) {` `            ``// If current node is not visited``            ``if` `(!vis[adj.get(v).get(i)]) {` `                ``// DFS call for current node``                ``dfs(adj.get(v).get(i), color, red, blue, sub_red, sub_blue, vis, adj);` `                ``// Count the total red and``            ``}``        ``}``    ``}` `    ``// Function to count the number of``    ``// subtree with the given condition``    ``static` `void` `countSubtree(``int``[] color, ``int` `n, ``int``[][] edge) {` `        ``// For creating adjacency list``        ``Map> adj = ``new` `HashMap<>();` `        ``// To store the count of subtree``        ``// with only blue and red color``        ``int``[] sub_red = ``new` `int``[n + ``3``];``        ``int``[] sub_blue = ``new` `int``[n + ``3``];` `        ``// visited array for DFS Traversal``        ``boolean``[] vis = ``new` `boolean``[n + ``3``];` `        ``// Count the number of red``        ``// node in the tree``        ``int` `red = countRed(color, n);` `        ``// Count the number of blue``        ``// node in the tree``        ``int` `blue = countBlue(color, n);` `        ``// Function Call to build tree``        ``buildTree(edge, adj, n);``        ``ans += ``4``;` `        ``// DFS Traversal``        ``dfs(``0``, color, red, blue, sub_red, sub_blue, vis, adj);` `        ``// Print the final count``        ``System.out.println(ans);``    ``}` `    ``// Test``    ``public` `static` `void` `main(String[] args) {``        ``int``[] color = {``1``, ``0``, ``0``, ``0``, ``2``};``        ``int` `n = ``5``;``        ``int``[][] edge = {{``1``,``2``},{``2``,``3``},{``3``,``4``},{``4``,``5``}};``        ``countSubtree(color,n,edge);``    ``}``}`

Output:
`4`

Time Complexity: O(N)
Auxiliary Space: O(N)

Previous
Next