VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-of-all-pair-shortest-paths-in-a-tree/

⇱ Sum of all pair shortest paths in a Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of all pair shortest paths in a Tree

Last Updated : 23 Jul, 2025

Given a weighted undirected graph T consisting of nodes valued [0, N - 1] and an array Edges[][3] of type {u, v, w} that denotes an edge between vertices u and v having weight w. The task is to find the sum of all pair shortest paths in the given tree.

Examples:

Input: N = 3, Edges[][] = {{0, 2, 15}, {1, 0, 90}}
Output: 210
Explanation: 
Sum of weights of path between nodes 0 and 1 = 90
Sum of weights of path between nodes 0 and 2 = 15
Sum of weights of path between nodes 1 and 2 = 105
Hence, sum = 90 + 15 + 105

Input: N = 4, Edges[][] = {{0, 1, 1}, {1, 2, 2}, {2, 3, 3}}
Output: 20
Explanation:
Sum of weights of path between nodes 0 and 1 = 1
Sum of weights of path between nodes 0 and 2 = 3
Sum of weights of path between nodes 0 and 3 = 6
Sum of weights of path between nodes 1 and 2 = 2
Sum of weights of path between nodes 1 and 3 = 5
Sum of weights of path between nodes 2 and 3 = 3
Hence, sum = 1 + 3 + 6 + 2 + 5 + 3 = 20.

Naive Approach: The simplest approach is to find the shortest path between every pair of vertices using the Floyd Warshall Algorithm. After precomputing the cost of the shortest path between every pair of nodes, print the sum of all the shortest paths.

Below is the implementation of the above approach:


Output
20

Time Complexity:O(N3), where N is the number of vertices.
Auxiliary Space: O(N)

Efficient Approach: The idea is to usethe DFS algorithm, using the DFS, for each vertex, the cost to visit every other vertex from this vertex can be found in linear time. Follow the below steps to solve the problem: 

  • Traverse the nodes 0 to N - 1.
  • For each node i, find the sum of the cost to visit every other vertex using DFS where the source will be node i, and let's denote this sum by Si.
  • Now, calculate S = S0 + S1 + ... + SN-1. and divide S by 2 because every path is calculated twice.
  • After completing the above steps, print the value of sum S obtained.

Below is the implementation of the above approach:


Output
20

Time Complexity: O(N2), where N is the number of vertices.
Auxiliary Space: O(N)

Comment