Given a tree as a set of edges such that every node has a unique value. We are also given a value k, the task is to count the unique paths in the tree such that every path has a value greater than K. A path value is said to be > K if every edge contributing to the path is connecting two nodes both of which have values > K.
Examples:Â
Input:Â
Â
Output: 9Â
Approach: The idea is to not form the tree with all the given edges. We only add an edge if it satisfies the condition of > k. In this case, a number of trees will be formed. While forming the different trees, we will only add the edge into the tree if both the node value are greater than K. After this, various numbers of trees will be created. Run a DFS for every node which in the end traverses the complete tree with which the node is attached and count the number of nodes in every tree. The number of unique paths for every tree which has X number of nodes is X * (X – 1) / 2.Â
Below is the implementation of the above approach:Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Function to count the number of nodes// in the tree using DFSint dfs(int node, int parent, list<int>* adj, bool vis[]){Â
    // Base case    int ans = 1;Â
    // Mark as visited    vis[node] = true;Â
    // Traverse for all children    for (auto it : adj[node]) {Â
        // If not equal to parent        if (it != parent)            ans += dfs(it, node, adj, vis);    }    return ans;}Â
// Function that returns the count of// unique pathsint countPaths(list<int>* adj, int k, int maxn){Â
    // An array that marks if the node    // is visited or not    bool vis[maxn + 1];    int ans = 0;Â
    // Initially marked as false    memset(vis, false, sizeof vis);Â
    // Traverse till max value of node    for (int i = 1; i <= maxn; i++) {Â
        // If not visited        if (!vis[i]) {Â
            // Get the number of nodes in that             // tree            int numNodes = dfs(i, 0, adj, vis);Â
            // Total unique paths in the current            // tree where numNodes is the total            // nodes in the tree            ans += numNodes * (numNodes - 1) / 2;        }    }    return ans;}Â
// Function to add edges to tree if value// is less than Kvoid addEdge(list<int>* adj, int u, int v, int k){Â Â Â Â if (u > k && v > k) {Â Â Â Â Â Â Â Â adj[u].push_back(v);Â Â Â Â Â Â Â Â adj[v].push_back(u);Â Â Â Â }}Â
// Driver codeint main(){Â Â Â Â int maxn = 12;Â
    list<int>* adj = new list<int>[maxn + 1];    int k = 3;Â
    // Create undirected edges    addEdge(adj, 2, 11, k);    addEdge(adj, 2, 6, k);    addEdge(adj, 5, 11, k);    addEdge(adj, 5, 10, k);    addEdge(adj, 5, 12, k);    addEdge(adj, 6, 7, k);    addEdge(adj, 6, 8, k);Â
    cout << countPaths(adj, k, maxn);Â
    return 0;} |
Java
// Java implementation of the approachimport java.util.*;Â
class GFG {Â
    // Function to count the number of nodes    // in the tree using DFS    static int dfs(int node, int parent,                 Vector<Integer>[] adj, boolean[] vis)     {Â
        // Base case        int ans = 1;Â
        // Mark as visited        vis[node] = true;Â
        // Traverse for all children        for (Integer it : adj[node])        {Â
            // If not equal to parent            if (it != parent)                ans += dfs(it, node, adj, vis);        }        return ans;    }Â
    // Function that returns the count of    // unique paths    static int countPaths(Vector<Integer>[] adj,                         int k, int maxn)    {Â
        // An array that marks if the node        // is visited or not        boolean[] vis = new boolean[maxn + 1];        int ans = 0;Â
        // Initially marked as false        Arrays.fill(vis, false);Â
        // Traverse till max value of node        for (int i = 1; i <= maxn; i++)        {Â
            // If not visited            if (!vis[i])             {Â
                // Get the number of nodes in that                // tree                int numNodes = dfs(i, 0, adj, vis);Â
                // Total unique paths in the current                // tree where numNodes is the total                // nodes in the tree                ans += numNodes * (numNodes - 1) / 2;            }        }        return ans;    }Â
    // Function to add edges to tree if value    // is less than K    static void addEdge(Vector<Integer>[] adj,                        int u, int v, int k)     {        if (u > k && v > k) {            adj[u].add(v);            adj[v].add(u);        }    }Â
    // Driver Code    public static void main(String[] args)    {        int maxn = 12;Â
        @SuppressWarnings("unchecked")        Vector<Integer>[] adj = new Vector[maxn + 1];        for (int i = 0; i < maxn + 1; i++)        {            adj[i] = new Vector<>();        }        int k = 3;Â
        // Create undirected edges        addEdge(adj, 2, 11, k);        addEdge(adj, 2, 6, k);        addEdge(adj, 5, 11, k);        addEdge(adj, 5, 10, k);        addEdge(adj, 5, 12, k);        addEdge(adj, 6, 7, k);        addEdge(adj, 6, 8, k);Â
        System.out.println(countPaths(adj, k, maxn));    }}Â
// This code is contributed by// sanjeev2552 |
Python3
# Python3 implementation of the approach Â
# Function to count the number of # nodes in the tree using DFS def dfs(node, parent, adj, vis): Â
    # Base case     ans = 1Â
    # Mark as visited     vis[node] = TrueÂ
    # Traverse for all children     for it in adj[node]: Â
        # If not equal to parent         if it != parent:             ans += dfs(it, node, adj, vis)          return ans Â
# Function that returns the # count of unique paths def countPaths(adj, k, maxn): Â
    # An array that marks if     # the node is visited or not     vis = [False] * (maxn + 1)     ans = 0Â
    # Traverse till max value of node     for i in range(1, maxn+1): Â
        # If not visited         if not vis[i]:Â
            # Get the number of             # nodes in that tree             numNodes = dfs(i, 0, adj, vis) Â
            # Total unique paths in the current             # tree where numNodes is the total             # nodes in the tree             ans += numNodes * (numNodes - 1) // 2             return ans Â
# Function to add edges to # tree if value is less than K def addEdge(adj, u, v, k): Â
    if u > k and v > k:        adj[u].append(v)         adj[v].append(u) Â
# Driver code if __name__ == "__main__":Â
    maxn = 12Â
    adj = [[] for i in range(maxn + 1)]     k = 3Â
    # Create undirected edges     addEdge(adj, 2, 11, k)     addEdge(adj, 2, 6, k)     addEdge(adj, 5, 11, k)     addEdge(adj, 5, 10, k)     addEdge(adj, 5, 12, k)     addEdge(adj, 6, 7, k)     addEdge(adj, 6, 8, k) Â
    print(countPaths(adj, k, maxn))Â
# This code is contributed by Rituraj Jain |
C#
// C# implementation of the approachusing System;using System.Collections.Generic;Â
class GFG{Â
// Function to count the number of nodes// in the tree using DFSstatic int dfs(int node, int parent,           List<int>[] adj, bool[] vis) {         // Base case    int ans = 1;Â
    // Mark as visited    vis[node] = true;Â
    // Traverse for all children    foreach(int it in adj[node])    {                 // If not equal to parent        if (it != parent)            ans += dfs(it, node, adj, vis);    }    return ans;}Â
// Function that returns the count of// unique pathsstatic int countPaths(List<int>[] adj, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int k, int maxn){Â
    // An array that marks if the node    // is visited or not    bool[] vis = new bool[maxn + 1];    int ans = 0;Â
    // Traverse till max value of node    for(int i = 1; i <= maxn; i++)    {                 // If not visited        if (!vis[i])         {                         // Get the number of nodes in that            // tree            int numNodes = dfs(i, 0, adj, vis);Â
            // Total unique paths in the current            // tree where numNodes is the total            // nodes in the tree            ans += numNodes * (numNodes - 1) / 2;        }    }    return ans;}Â
// Function to add edges to tree if value// is less than Kstatic void addEdge(List<int>[] adj,                    int u, int v, int k) {    if (u > k && v > k)     {        adj[u].Add(v);        adj[v].Add(u);    }}Â
// Driver Codepublic static void Main(String[] args){Â Â Â Â int maxn = 12;Â
    List<int>[] adj = new List<int>[maxn + 1];    for(int i = 0; i < maxn + 1; i++)    {        adj[i] = new List<int>();    }    int k = 3;Â
    // Create undirected edges    addEdge(adj, 2, 11, k);    addEdge(adj, 2, 6, k);    addEdge(adj, 5, 11, k);    addEdge(adj, 5, 10, k);    addEdge(adj, 5, 12, k);    addEdge(adj, 6, 7, k);    addEdge(adj, 6, 8, k);Â
    Console.WriteLine(countPaths(adj, k, maxn));}}Â
// This code is contributed by Princi Singh |
Javascript
<script>Â
    // JavaScript implementation of the approach         // Function to count the number of nodes    // in the tree using DFS    function dfs(node, parent, adj, vis)    {          // Base case        let ans = 1;          // Mark as visited        vis[node] = true;          // Traverse for all children        for (let it = 0; it < adj[node].length; it++)        {              // If not equal to parent            if (adj[node][it] != parent)                ans += dfs(adj[node][it], node, adj, vis);        }        return ans;    }      // Function that returns the count of    // unique paths    function countPaths(adj, k, maxn)    {          // An array that marks if the node        // is visited or not        let vis = new Array(maxn + 1);        let ans = 0;          // Initially marked as false        vis.fill(false);          // Traverse till max value of node        for (let i = 1; i <= maxn; i++)        {              // If not visited            if (!vis[i])            {                  // Get the number of nodes in that                // tree                let numNodes = dfs(i, 0, adj, vis);                  // Total unique paths in the current                // tree where numNodes is the total                // nodes in the tree                ans += numNodes * (numNodes - 1) / 2;            }        }        return ans;    }      // Function to add edges to tree if value    // is less than K    function addEdge(adj, u, v, k)    {        if (u > k && v > k) {            adj[u].push(v);            adj[v].push(u);        }    }         let maxn = 12;      let adj = new Array(maxn + 1);    for (let i = 0; i < maxn + 1; i++)    {      adj[i] = [];    }    let k = 3;Â
    // Create undirected edges    addEdge(adj, 2, 11, k);    addEdge(adj, 2, 6, k);    addEdge(adj, 5, 11, k);    addEdge(adj, 5, 10, k);    addEdge(adj, 5, 12, k);    addEdge(adj, 6, 7, k);    addEdge(adj, 6, 8, k);Â
    document.write(countPaths(adj, k, maxn));     </script> |
9
Â
Time Complexity: O(N), as we are using recursion to traverse N times. Where N is the total number of nodes.
Auxiliary Space: O(N), as we are using extra space for the visited array. Where N is the total number of nodes.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

