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.

**Examples:**

Input:N = 5, E = 4, Q = 3

1

(4) / \ (2)

/ \

42

(5)/ \ (3)

/ \

53

Query 1:S=1

Query 2: S = 3

Query 3: S = 5Output :

16

17

19Explanation :

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

1

(9) / \ (1)

/ \

23

Query 1:S=1

Query 2: S = 2

Query 3: S = 3Output :

10

10

10

**Naive Approach:**

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 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
- dp[i] += ( dp[a] – dp[i] ) + ( weight of edge between nodes(a, i) ) * ( L – leaves[i] ) ;
- leaves[i] += L ;

- L

Below is the implementation of the above approach:

## CPP

`// CPP program for the above problem ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `// MAX size ` `const` `int` `N = 1e5 + 5; ` ` ` `// graph with {destination, weight}; ` `vector<vector<pair<` `int` `, ` `int` `> > > v(N); ` ` ` `// for storing the sum for ith node ` `vector<` `int` `> dp(N); ` ` ` `// leaves in subtree of ith. ` `vector<` `int` `> leaves(N); ` `int` `n; ` ` ` `// dfs to find sum of distance ` `// of leaves in the ` `// subtree of a node ` `void` `dfs(` `int` `a, ` `int` `par) ` `{ ` ` ` `// flag is the node is ` ` ` `// leaf or not; ` ` ` `bool` `leaf = 1; ` ` ` `for` `(` `auto` `& i : v[a]) { ` ` ` `// skipping if parent ` ` ` `if` `(i.first == par) ` ` ` `continue` `; ` ` ` ` ` `// setting flag to false ` ` ` `leaf = 0; ` ` ` ` ` `// doing dfs call ` ` ` `dfs(i.first, a); ` ` ` `} ` ` ` ` ` `// doing calculation ` ` ` `// in postorder. ` ` ` `if` `(leaf == 1) { ` ` ` ` ` `// if the node is leaf then ` ` ` `// we just increment ` ` ` `// the no. of leaves under ` ` ` `// the subtree of a node ` ` ` `leaves[a] += 1; ` ` ` `} ` ` ` `else` `{ ` ` ` ` ` `for` `(` `auto` `& i : v[a]) { ` ` ` `if` `(i.first == par) ` ` ` `continue` `; ` ` ` ` ` `// adding num of leaves ` ` ` `leaves[a] ` ` ` `+= leaves[i.first]; ` ` ` ` ` `// calculating answer for ` ` ` `// the sum in the subtree ` ` ` `dp[a] = dp[a] ` ` ` `+ dp[i.first] ` ` ` `+ leaves[i.first] ` ` ` `* i.second; ` ` ` `} ` ` ` `} ` `} ` ` ` `// dfs function to find the ` `// sum of distance of leaves ` `// outside the subtree ` `void` `dfs2(` `int` `a, ` `int` `par) ` `{ ` ` ` `for` `(` `auto` `& i : v[a]) { ` ` ` `if` `(i.first == par) ` ` ` `continue` `; ` ` ` ` ` `// number of leaves other ` ` ` `// than the leaves in the ` ` ` `// subtree of i ` ` ` `int` `leafOutside = leaves[a] - leaves[i.first]; ` ` ` ` ` `// adding the contribution ` ` ` `// of leaves outside to ` ` ` `// the ith node ` ` ` `dp[i.first] += (dp[a] - dp[i.first]); ` ` ` ` ` `dp[i.first] += i.second ` ` ` `* (leafOutside ` ` ` `- leaves[i.first]); ` ` ` ` ` `// adding the leafs outside ` ` ` `// to ith node's leaves. ` ` ` `leaves[i.first] ` ` ` `+= leafOutside; ` ` ` `dfs2(i.first, a); ` ` ` `} ` `} ` ` ` `void` `answerQueries( ` ` ` `vector<` `int` `> queries) ` `{ ` ` ` ` ` `// calculating the sum of ` ` ` `// distance of leaves in the ` ` ` `// subtree of a node assuming ` ` ` `// the root of the tree is 1 ` ` ` `dfs(1, 0); ` ` ` ` ` `// calculating the sum of ` ` ` `// distance of leaves outside ` ` ` `// the subtree of node ` ` ` `// assuming the root of the ` ` ` `// tree is 1 ` ` ` `dfs2(1, 0); ` ` ` ` ` `// answering the queries; ` ` ` `for` `(` `int` `i = 0; ` ` ` `i < queries.size(); i++) { ` ` ` `cout << dp[queries[i]] << endl; ` ` ` `} ` `} ` ` ` `// Driver Code ` `int` `main() ` `{ ` ` ` `// Driver Code ` ` ` `/* ` ` ` `1 ` ` ` `(4) / \ (2) ` ` ` `/ \ ` ` ` `4 2 ` ` ` `(5)/ \ (3) ` ` ` `/ \ ` ` ` `5 3 ` ` ` `*/` ` ` ` ` `n = 5; ` ` ` ` ` `// initialising tree ` ` ` `v[1].push_back( ` ` ` `make_pair(4, 4)); ` ` ` `v[4].push_back( ` ` ` `make_pair(1, 4)); ` ` ` `v[1].push_back( ` ` ` `make_pair(2, 2)); ` ` ` `v[2].push_back( ` ` ` `make_pair(1, 2)); ` ` ` `v[2].push_back( ` ` ` `make_pair(3, 3)); ` ` ` `v[3].push_back( ` ` ` `make_pair(2, 3)); ` ` ` `v[2].push_back( ` ` ` `make_pair(5, 5)); ` ` ` `v[5].push_back( ` ` ` `make_pair(2, 5)); ` ` ` ` ` `vector<` `int` `> ` ` ` `queries = { 1, 3, 5 }; ` ` ` `answerQueries(queries); ` `} ` |

*chevron_right*

*filter_none*

**Output:**

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.

## Recommended Posts:

- Count of leaf nodes of the tree whose weighted string is a palindrome
- Minimum difference between any two weighted nodes in Sum Tree of the given Tree
- Minimum distance to visit all the nodes of an undirected weighted tree
- Print the longest leaf to leaf path in a Binary tree
- Number of leaf nodes in the subtree of every node of an n-ary tree
- Check whether a node is leaf node or not for multiple queries
- Find distance between two nodes in the given Binary tree for Q queries
- Find the root of the sub-tree whose weighted sum XOR with X is maximum
- Find the root of the sub-tree whose weighted sum is minimum
- Find the root of the sub-tree whose weighted sum XOR with X is minimum
- Count pairs of leaf nodes in a Binary Tree which are at most K distance apart
- Queries to find distance between two nodes of a Binary tree
- Queries to find distance between two nodes of a Binary tree - O(logn) method
- Find distance of nodes from root in a tree for multiple queries
- Print all nodes that are at distance k from a leaf node
- Find root of the tree where children id sum for every node is given
- Count the nodes of the given tree whose weighted string is a palindrome
- Count the nodes of a tree whose weighted string is an anagram of the given string
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.