Skip to content

834. Sum of Distances in Tree 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
 public:
  vector<int> sumOfDistancesInTree(int n, vector<vector<int>>& edges) {
    vector<int> ans(n);
    vector<int> count(n, 1);
    vector<unordered_set<int>> tree(n);

    for (const vector<int>& edge : edges) {
      const int u = edge[0];
      const int v = edge[1];
      tree[u].insert(v);
      tree[v].insert(u);
    }

    postorder(tree, 0, /*prev=*/-1, count, ans);
    preorder(tree, 0, /*prev=*/-1, count, ans);
    return ans;
  }

 private:
  void postorder(const vector<unordered_set<int>>& tree, int u, int prev,
                 vector<int>& count, vector<int>& ans) {
    for (const int v : tree[u]) {
      if (v == prev)
        continue;
      postorder(tree, v, u, count, ans);
      count[u] += count[v];
      ans[u] += ans[v] + count[v];
    }
  }

  void preorder(const vector<unordered_set<int>>& tree, int u, int prev,
                vector<int>& count, vector<int>& ans) {
    for (const int v : tree[u]) {
      if (v == prev)
        continue;
      // count[v] us are 1 step closer from v than prev.
      // (n - count[v]) us are 1 step farther from v than prev.
      ans[v] = ans[u] - count[v] + (tree.size() - count[v]);
      preorder(tree, v, u, count, ans);
    }
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
  public int[] sumOfDistancesInTree(int n, int[][] edges) {
    int[] ans = new int[n];
    int[] count = new int[n];
    Set<Integer>[] tree = new Set[n];

    Arrays.fill(count, 1);

    for (int i = 0; i < n; ++i)
      tree[i] = new HashSet<>();

    for (int[] edge : edges) {
      final int u = edge[0];
      final int v = edge[1];
      tree[u].add(v);
      tree[v].add(u);
    }

    postorder(tree, 0, -1, count, ans);
    preorder(tree, 0, -1, count, ans);
    return ans;
  }

  private void postorder(Set<Integer>[] tree, int u, int prev, int[] count, int[] ans) {
    for (final int v : tree[u]) {
      if (v == prev)
        continue;
      postorder(tree, v, u, count, ans);
      count[u] += count[v];
      ans[u] += ans[v] + count[v];
    }
  }

  private void preorder(Set<Integer>[] tree, int u, int prev, int[] count, int[] ans) {
    for (final int v : tree[u]) {
      if (v == prev)
        continue;
      // count[v] us are 1 step closer from v than prev.
      // (n - count[v]) us are 1 step farther from v than prev.
      ans[v] = ans[u] - count[v] + (tree.length - count[v]);
      preorder(tree, v, u, count, ans);
    }
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution:
  def sumOfDistancesInTree(self, n: int, edges: list[list[int]]) -> list[int]:
    ans = [0] * n
    count = [1] * n
    tree = [set() for _ in range(n)]

    for u, v in edges:
      tree[u].add(v)
      tree[v].add(u)

    def postorder(u: int, prev: int) -> None:
      for v in tree[u]:
        if v == prev:
          continue
        postorder(v, u)
        count[u] += count[v]
        ans[u] += ans[v] + count[v]

    def preorder(u: int, prev: int) -> None:
      for v in tree[u]:
        if v == prev:
          continue
        # count[v] us are 1 step closer from v than prev.
        # (n - count[v]) us are 1 step farther from v than prev.
        ans[v] = ans[u] - count[v] + (n - count[v])
        preorder(v, u)

    postorder(0, -1)
    preorder(0, -1)
    return ans