LeetCode 834: Sum of Distances in Tree Solution

Master LeetCode problem 834 (Sum of Distances in Tree), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

834. Sum of Distances in Tree

Problem Explanation

Explanation:

To solve this problem, we can use a depth-first search (DFS) approach. We need to calculate the sum of distances for each node in the tree. The idea is to calculate two values for each node:

  1. count[node]: the number of nodes in the subtree rooted at node.
  2. res[node]: the sum of distances from node to all other nodes.

We start by doing a post-order traversal to calculate count and res for each node. Then, using the values calculated during the post-order traversal, we do a pre-order traversal to update the res values for all nodes by propagating the information from their parent nodes. :

Solution Code

class Solution {
    int[] res, count;
    List<Set<Integer>> tree;
    
    public int[] sumOfDistancesInTree(int n, int[][] edges) {
        res = new int[n];
        count = new int[n];
        tree = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            tree.add(new HashSet<>());
        }
        
        for (int[] edge : edges) {
            tree.get(edge[0]).add(edge[1]);
            tree.get(edge[1]).add(edge[0]);
        }
        
        postOrder(0, -1);
        preOrder(0, -1);
        
        return res;
    }
    
    private void postOrder(int node, int parent) {
        for (int child : tree.get(node)) {
            if (child == parent) continue;
            postOrder(child, node);
            count[node] += count[child];
            res[node] += res[child] + count[child];
        }
        count[node]++;
    }
    
    private void preOrder(int node, int parent) {
        for (int child : tree.get(node)) {
            if (child == parent) continue;
            res[child] = res[node] - count[child] + count.length - count[child];
            preOrder(child, node);
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 834 (Sum of Distances in Tree)?

This page provides optimized solutions for LeetCode problem 834 (Sum of Distances in Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 834 (Sum of Distances in Tree)?

The time complexity for LeetCode 834 (Sum of Distances in Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 834 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 834 in Java, C++, or Python.

Back to LeetCode Solutions