Queries to find sum of distance of a given node to every leaf node in a Weighted Tree
Given a Undirected Weighted Tree having N nodes and E edges. Given Q queries, with each query indicating a starting node. The task is to print the sum of the distances from a given starting node S to every leaf node in the Weighted Tree.
Input: N = 5, E = 4, Q = 3
(4) / \ (2)
(5)/ \ (3)
Query 1: S = 1
Query 2: S = 3
Query 3: S = 5
The three leaf nodes in the tree are 3, 4 and 5.
For S = 1, the sum of the distances from node 1 to the leaf nodes are: d(1, 4) + d(1, 3) + d(1, 5) = 4 + (2 + 5) + (2 + 3) = 16.
For S = 3, the sum of the distances from node 3 to its leaf nodes are: d(3, 4) + d(3, 3) + d(3, 5) = (3 + 2 + 4) + 0 + (3 + 5) = 17
For S = 5, the sum of the distances from node 5 to its leaf nodes are: d(5, 4) + d(5, 3) + d(5, 5) = (5 + 2 + 4) + (5 + 3) + 0 = 19
Input: N = 3, E = 2, Q = 2
(9) / \ (1)
Query 1: S = 1
Query 2: S = 2
Query 3: S = 3
For each query, traverse the entire tree and find the sum of the distance from the given source node to all the leaf nodes.
Time Complexity: O(Q * N)
Efficient Approach: The idea is to use pre-compute the sum of the distance of every node to all the leaf nodes using Dynamic Programming on trees Algorithm and obtain the answer for each query in constant time.
Follow the steps below to solve the problem
- Initialize a vector dp to store the sum of the distances from each node i to all the leaf nodes of the tree.
- Initialize a vector leaves to store the count of the leaf nodes in the sub-tree of node i considering 1 as the root node.
- Find the sum of the distances from node i to all the leaf nodes in the sub-tree of i considering 1 as the root node using a modified Depth First Search Algorithm.
Let node a be the parent of node i
- leaves[a] += leaves[i] ;
- dp[a] += dp[i] + leaves[i] * weight of edge between nodes(a, i) ;
- Use the re-rooting technique to find the distance of the remaining leaves of the tree that are not in the sub-tree of node i. To calculate these distances, use another modified Depth First Search (DFS) algorithm to find and add the sum of the distances of leaf nodes to node i.
Let a be the parent node and i be the child node, then
Let the number of leaf nodes outside the sub-tree i that are present in the sub-tree a be L
- L = leaves[a] – leaves[i] ;
- dp[i] += ( dp[a] – dp[i] ) + ( weight of edge between nodes(a, i) ) * ( L – leaves[i] ) ;
- leaves[i] += L ;
Below is the implementation of the above approach:
16 17 19
Time Complexity: O(N + Q)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.