AlgoMaster Logo

Sum of Distances in Tree

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force using DFS

Intuition:

The brute force approach calculates the distance for each node by performing a Depth First Search (DFS) from each node to every other node. This gives a clear idea of the problem but is inefficient due to repeatedly traversing the tree for each node.

Steps:

  1. For each node in the tree, calculate the sum of distances to all other nodes by performing a DFS traversal.
  2. Maintain a graph representation using adjacency lists for bi-directional traversal.
  3. After computing the distance sum for one node, repeat the procedure for all nodes.

This approach is clear but inefficient due to repeated calculations, making it not suitable for larger trees.

Code:

2. Optimized DFS with DP and Precomputation

Intuition:

To optimize, we use dynamic programming and precompute sub-tree information to reuse calculations efficiently. We perform two DFS traversals, where the first one calculates the sum of distances from an arbitrary root (e.g., node 0) to all its sub-nodes, and the second adjusts these values from the root to other nodes using precomputed information.

Steps:

  1. Perform a first DFS to calculate:
    • count[node]: number of nodes in the subtree rooted at node.
    • answer[0]: initial sum of distances from root node to all other nodes.
  2. Execute a second DFS to propagate these sums effectively to the rest of the nodes and adjust them using the precomputed values:
    • For each node transitioning from parent, calculate its sum based on the child's distance by subtracting its distance contributed and adding distances from non-subtree nodes.

Code: