Open In App

Minimum difference between any two weighted nodes in Sum Tree of the given Tree

Last Updated : 28 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a tree of N nodes, the task is to convert the given tree to its Sum Tree(including its own weight) and find the minimum difference between any two node’s weight of the sum tree.

Note: The N nodes of the given tree are given in the form of top to bottom with N-1 line where each line describes two nodes that are connected. 

Examples:

Input: 
 

Output: 1
Explanation: 
total weight of node 1: 3 (own weight) + (10 + 6 + 5 + 8 + 2 + 7 + 11) (sub-tree node’s weight) = 52 
total weight of node 2: 5 (own weight) + (2 + 7 + 11) (sub-tree node’s weight) = 25 
total weight of node 3: 8 (own weight) + (0) (sub-tree node’s weight) = 8 
total weight of node 4: 10 (own weight) + (0) (sub-tree node’s weight) = 10 
total weight of node 5: 2 (own weight) + (0) (sub-tree node’s weight) = 2 
total weight of node 6: 6 (own weight) + (5 + 8 + 2 + 7 + 11) (sub-tree node’s weight) = 39 
total weight of node 7: 7 (own weight) + (0) (sub-tree node’s weight) = 7 
total weight of node 8: 11 (own weight) + (0) (sub-tree node’s weight) = 11
By observing the total weight of each node, Node 4 and 8 have a minimum difference(11-10) = 1

Input: 
 

Output: 0

Approach: 

  1. We will traverse the given tree from below and store the weight of that node plus its sub-tree node’s weight in one array and mark the index of each node as visited. So in between, if we revisit that node then we don’t have to count the weight of that node again.
  2. We will sort the array where we have stored the total weight of each node.
  3. Now find the pairwise difference in the sorted array and whichever pair gave minimum difference print that minimum difference at last.

Below is the implementation of the above approach: 

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find minimum
// difference between any two node
void MinimumDifference(int total_weight[],
                       int N)
{
    int min_difference = INT_MAX;
 
    for (int i = 1; i < N; i++) {
 
        // Pairwise difference
        if (total_weight[i]
                - total_weight[i - 1]
            < min_difference) {
            min_difference
                = total_weight[i]
                  - total_weight[i - 1];
        }
    }
 
    cout << min_difference << endl;
}
 
// Function to find total weight
// of each individual node
void SumTree(vector<pair<int, int> > v,
             int individual_weight[],
             int N)
{
    // Array to store total weight
    // of each node from 1 to N
    int total_weight[N] = { 0 };
 
    // Array to keep track of node
    // previously counted or not
    int visited[N] = { 0 };
 
    // To store node no. from
    /// N-1 lines
    int first, second;
 
    // To traverse from (N-1)
    // line to 1 line
    for (int i = (N - 2); i >= 0; i--) {
        first = v[i].first;
        second = v[i].second;
 
        // Node is note visited
        if (visited[second - 1] == 0) {
 
            total_weight[second - 1]
                += individual_weight[second - 1];
 
            // Make node visited
            visited[second - 1] = 1;
        }
 
        total_weight[first - 1]
            += total_weight[second - 1];
 
        // Node is note visited
        if (visited[first - 1] == 0) {
 
            total_weight[first - 1]
                += individual_weight[first - 1];
 
            // Make node visited
            visited[first - 1] = 1;
        }
    }
 
    // Sort the total weight of each node
    sort(total_weight, total_weight + N);
 
    // Call function to find minimum
    // difference
    MinimumDifference(total_weight, N);
}
 
// Driver code
int main()
{
    // Total node of rooted tree
    int N = 8;
 
    vector<pair<int, int> > v;
 
    // N-1 lines describing
    // rooted tree from top
    // to bottom
    v.push_back(make_pair(1, 4));
    v.push_back(make_pair(1, 6));
    v.push_back(make_pair(6, 2));
    v.push_back(make_pair(6, 3));
    v.push_back(make_pair(2, 5));
    v.push_back(make_pair(2, 7));
    v.push_back(make_pair(2, 8));
 
    // Array describing weight
    // of each node from 1 to N
    int individual_weight[N] = { 3, 5, 8, 10,
                                 2, 6, 7, 11 };
 
    SumTree(v, individual_weight, N);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
static class pair
{
    int first, second;
    public pair(int first, int second) 
    {
        this.first = first;
        this.second = second;
    }   
}
 
// Function to find minimum
// difference between any two node
static void MinimumDifference(int total_weight[],
                              int N)
{
    int min_difference = Integer.MAX_VALUE;
 
    for(int i = 1; i < N; i++)
    {
         
        // Pairwise difference
        if (total_weight[i] -
            total_weight[i - 1] <
            min_difference)
        {
            min_difference = total_weight[i] -
                             total_weight[i - 1];
        }
    }
 
    System.out.print(min_difference + "\n");
}
 
// Function to find total weight
// of each individual node
static void SumTree(Vector<pair> v,
                    int individual_weight[],
                    int N)
{
     
    // Array to store total weight
    // of each node from 1 to N
    int total_weight[] = new int[N];
 
    // Array to keep track of node
    // previously counted or not
    int visited[] = new int[N];
 
    // To store node no. from
    /// N-1 lines
    int first, second;
 
    // To traverse from (N-1)
    // line to 1 line
    for(int i = (N - 2); i >= 0; i--)
    {
        first = v.get(i).first;
        second = v.get(i).second;
 
        // Node is note visited
        if (visited[second - 1] == 0)
        {
            total_weight[second - 1] +=
            individual_weight[second - 1];
 
            // Make node visited
            visited[second - 1] = 1;
        }
 
        total_weight[first - 1] +=
        total_weight[second - 1];
 
        // Node is note visited
        if (visited[first - 1] == 0)
        {
            total_weight[first - 1] +=
            individual_weight[first - 1];
 
            // Make node visited
            visited[first - 1] = 1;
        }
    }
 
    // Sort the total weight of each node
    Arrays.sort(total_weight);
 
    // Call function to find minimum
    // difference
    MinimumDifference(total_weight, N);
}
 
// Driver code
public static void main(String[] args)
{
     
    // Total node of rooted tree
    int N = 8;
 
    Vector<pair> v = new Vector<>();
 
    // N-1 lines describing
    // rooted tree from top
    // to bottom
    v.add(new pair(1, 4));
    v.add(new pair(1, 6));
    v.add(new pair(6, 2));
    v.add(new pair(6, 3));
    v.add(new pair(2, 5));
    v.add(new pair(2, 7));
    v.add(new pair(2, 8));
 
    // Array describing weight
    // of each node from 1 to N
    int individual_weight[] = { 3, 5, 8, 10,
                                2, 6, 7, 11 };
 
    SumTree(v, individual_weight, N);
}
}
 
// This code is contributed by Amit Katiyar


Python3




# Python3 program for the above approach
import sys
 
# Function to find minimum difference
# between any two node
def minimum_difference(total_weight, n):
     
    min_difference = sys.maxsize
     
    for i in range(1, n):
         
        # Pairwise difference
        if (total_weight[i] -
            total_weight[i - 1] <
            min_difference):
            min_difference = (total_weight[i] -
                              total_weight[i - 1])
    print(min_difference)
 
# Function to find total weight
# of each individual node
def SumTree(v, individual_weight, N):
     
    # Array to store total weight of
    # each node from 1 to n
    total_weight = [0 for i in range(N)]
     
    # Array to keep track of node
    # previously counted or not
    visited = [0 for i in range(N)]
     
    # To traverse from (n-1) line to 1 line
    for i in range(N - 2, -1, -1):
        first = v[i][0]
        second = v[i][1]
         
        if visited[second - 1] == 0:
            total_weight[second - 1] += (
            individual_weight[second - 1])
             
            # Make node visited
            visited[second - 1] = 1
             
        total_weight[first - 1] += (
        total_weight[second - 1])
         
        # Node is note visited
        if visited[first - 1] == 0:
            total_weight[first - 1] += (
            individual_weight[first - 1])
             
            # Make node visited
            visited[first - 1] = 1
             
    # Sort the total weight of each node
    total_weight.sort()
     
    # Call function to find minimum difference
    minimum_difference(total_weight, n)
     
# Driver Code
if __name__=='__main__':
     
    # Total node of rooted tree
    n = 8
    v = []
     
    # n-1 lines describing rooted
    # tree from top to bottom
    v.append([1, 4])
    v.append([1, 6])
    v.append([6, 2])
    v.append([6, 3])
    v.append([2, 5])
    v.append([2, 7])
    v.append([2, 8])
 
    # Array describing weight of each
    # node from 1 to n
    individual_weight = [ 3, 5, 8, 10,
                          2, 6, 7, 11 ]
 
    SumTree(v, individual_weight, n)
 
# This code is contributed by rutvik_56


C#




// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
 
class pair
{
  public int first,
             second;
  public pair(int first,
              int second) 
  {
    this.first = first;
    this.second = second;
  }   
}
 
// Function to find minimum
// difference between any two node
static void MinimumDifference(int []total_weight,
                              int N)
{
  int min_difference = int.MaxValue;
 
  for(int i = 1; i < N; i++)
  {
    // Pairwise difference
    if (total_weight[i] -
        total_weight[i - 1] <
        min_difference)
    {
      min_difference = total_weight[i] -
                       total_weight[i - 1];
    }
  }
 
  Console.Write(min_difference + "\n");
}
 
// Function to find total weight
// of each individual node
static void SumTree(List<pair> v,
                    int []individual_weight,
                    int N)
{   
  // Array to store total weight
  // of each node from 1 to N
  int []total_weight = new int[N];
 
  // Array to keep track of node
  // previously counted or not
  int []visited = new int[N];
 
  // To store node no. from
  /// N-1 lines
  int first, second;
 
  // To traverse from (N-1)
  // line to 1 line
  for(int i = (N - 2); i >= 0; i--)
  {
    first = v[i].first;
    second = v[i].second;
 
    // Node is note visited
    if (visited[second - 1] == 0)
    {
      total_weight[second - 1] +=
            individual_weight[second - 1];
 
      // Make node visited
      visited[second - 1] = 1;
    }
 
    total_weight[first - 1] +=
          total_weight[second - 1];
 
    // Node is note visited
    if (visited[first - 1] == 0)
    {
      total_weight[first - 1] +=
            individual_weight[first - 1];
 
      // Make node visited
      visited[first - 1] = 1;
    }
  }
 
  // Sort the total weight
  // of each node
  Array.Sort(total_weight);
 
  // Call function to find minimum
  // difference
  MinimumDifference(total_weight, N);
}
 
// Driver code
public static void Main(String[] args)
{   
  // Total node of rooted tree
  int N = 8;
 
  List<pair> v = new List<pair>();
 
  // N-1 lines describing
  // rooted tree from top
  // to bottom
  v.Add(new pair(1, 4));
  v.Add(new pair(1, 6));
  v.Add(new pair(6, 2));
  v.Add(new pair(6, 3));
  v.Add(new pair(2, 5));
  v.Add(new pair(2, 7));
  v.Add(new pair(2, 8));
 
  // Array describing weight
  // of each node from 1 to N
  int []individual_weight = {3, 5, 8, 10,
                             2, 6, 7, 11};
 
  SumTree(v, individual_weight, N);
}
}
 
// This code is contributed by shikhasingrajput


Javascript




<script>
    // Javascript program for the above approach
     
    // Function to find minimum
    // difference between any two node
    function MinimumDifference(total_weight, N)
    {
        let min_difference = Number.MAX_VALUE;
 
        for (let i = 1; i < N; i++) {
 
            // Pairwise difference
            if (total_weight[i]
                    - total_weight[i - 1]
                < min_difference) {
                min_difference
                    = total_weight[i]
                      - total_weight[i - 1];
            }
        }
 
        document.write(min_difference + "</br>");
    }
 
    // Function to find total weight
    // of each individual node
    function SumTree(v, individual_weight, N)
    {
        // Array to store total weight
        // of each node from 1 to N
        let total_weight = new Array(N);
        total_weight.fill(0);
 
        // Array to keep track of node
        // previously counted or not
        let visited = new Array(N);
        visited.fill(0);
 
        // To store node no. from
        /// N-1 lines
        let first, second;
 
        // To traverse from (N-1)
        // line to 1 line
        for (let i = (N - 2); i >= 0; i--) {
            first = v[i][0];
            second = v[i][1];
 
            // Node is note visited
            if (visited[second - 1] == 0) {
 
                total_weight[second - 1]
                    += individual_weight[second - 1];
 
                // Make node visited
                visited[second - 1] = 1;
            }
 
            total_weight[first - 1]
                += total_weight[second - 1];
 
            // Node is note visited
            if (visited[first - 1] == 0) {
 
                total_weight[first - 1]
                    += individual_weight[first - 1];
 
                // Make node visited
                visited[first - 1] = 1;
            }
        }
 
        // Sort the total weight of each node
        total_weight.sort(function(a, b){return a - b});
 
        // Call function to find minimum
        // difference
        MinimumDifference(total_weight, N);
    }
     
    // Total node of rooted tree
    let N = 8;
  
    let v = [];
  
    // N-1 lines describing
    // rooted tree from top
    // to bottom
    v.push([1, 4]);
    v.push([1, 6]);
    v.push([6, 2]);
    v.push([6, 3]);
    v.push([2, 5]);
    v.push([2, 7]);
    v.push([2, 8]);
  
    // Array describing weight
    // of each node from 1 to N
    let individual_weight = [ 3, 5, 8, 10, 2, 6, 7, 11 ];
  
    SumTree(v, individual_weight, N);
 
// This code is contributed by decode2207.
</script>


Output: 

1

 

Time Complexity: O(N * Log(N)), where N is the total of nodes in the rooted tree.
Auxiliary Space: O(N)



Similar Reads

Minimum cost of path between given nodes containing at most K nodes in a directed and weighted graph
Given a directed weighted graph represented by a 2-D array graph[][] of size n and 3 integers src, dst, and k representing the source point, destination point, and the available number of stops. The task is to minimize the cost of the path between two nodes containing at most K nodes in a directed and weighted graph. If there is no such route, retu
10 min read
Shortest distance between given nodes in a bidirectional weighted graph by removing any K edges
Given a positive integer K and a weighted undirected connected graph of N nodes and E edges as an array Edges[] of the type {u, v, W} representing the edges between Node u and Node v having weight W, the task is to find the shortest distance between the two given nodes S and D after reducing the cost of at most K edges to 0.  Examples: Input: N = 5
24 min read
Minimum Cost of Simple Path between two nodes in a Directed and Weighted Graph
Given a directed graph, which may contain cycles, where every edge has weight, the task is to find the minimum cost of any simple path from a given source vertex ‘s’ to a given destination vertex ‘t’. Simple Path is the path from one vertex to another such that no vertex is visited more than once. If there is no simple path possible then return INF
10 min read
Count the nodes of a tree whose weighted string does not contain any duplicate characters
Given a tree, and the weights (in the form of strings) of all the nodes, the task is to count the nodes whose weights do not contain any duplicate character.Examples: Input: Output: 2 Only the strings of the node 1 and 4 contains unique strings. Approach: Perform dfs on the tree and for every node, check if its string contains duplicate char or not
5 min read
Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
Given an N-ary tree with weighted edge and Q queries where each query contains two nodes of the tree. The task is to find the maximum weighted edge in the simple path between these two nodes.Examples: Naive Approach: A simple solution is to traverse the whole tree for each query and find the path between the two nodes.Efficient Approach: The idea i
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, 2, 50, 5} Output: 73 Input: u[] = {1, 2} v[] = {2,
10 min read
Count the nodes of a tree whose weighted string is an anagram of the given string
Given a tree, and the weights (in the form of strings) of all the nodes, the task is to count the nodes whose weighted string is an anagram with the given string str.Examples: Input: str = "geek" Output: 2 Only the weighted strings of the nodes 2 and 6 are anagrams of the given string "geek". Approach: Perform dfs on the tree and for every node, ch
6 min read
Count the nodes of the given tree whose weighted string is a palindrome
Given a tree, and the weights (in the form of strings) of all the nodes, the task is to count the nodes whose weights are palindrome. Examples: Input: Output: 3Only the weights of the nodes 2, 3 and 5 are palindromes.Recommended: Please try your approach on {IDE} first, before moving on to the solution.Approach: Perform dfs on the tree and for ever
9 min read
Common nodes in the inorder sequence of a tree between given two nodes in O(1) space
Given a binary tree consisting of distinct values and two numbers K1 and K2, the task is to find all nodes that lie between them in the inorder sequence of the tree. Examples: Input: 1 / \ 12 11 / / \ 3 4 13 \ / 15 9 k1 = 12 k2 = 15 Output: 1 4 Explanation: Inorder sequence is 3 12 1 4 15 11 9 13 The common nodes between 12 and 15 in the inorder se
10 min read
Minimum cost to connect weighted nodes represented as array
Given an array of N elements(nodes), where every element is weight of that node.Connecting two nodes will take a cost of product of their weights.You have to connect every node with every other node(directly or indirectly).Output the minimum cost required.Examples: Input : a[] = {6, 2, 1, 5} Output : 13 Explanation : Here, we connect the nodes as f
4 min read