LeetCode Solutions

834. Sum of Distances in Tree

Time: $O(n)$

Space: $O(n)$

			

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>& e : edges) {
      const int u = e[0];
      const int v = e[1];
      tree[u].insert(v);
      tree[v].insert(u);
    }

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

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

  void preorder(const vector<unordered_set<int>>& tree, int node, int parent,
                vector<int>& count, vector<int>& ans) {
    for (const int child : tree[node]) {
      if (child == parent)
        continue;
      // count[child] nodes are 1 step closer from child than parent
      // (N - count[child]) nodes are 1 step farther from child than parent
      ans[child] = ans[node] - count[child] + (tree.size() - count[child]);
      preorder(tree, child, node, count, ans);
    }
  }
};
			

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[] e : edges) {
      final int u = e[0];
      final int v = e[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 node, int parent, int[] count, int[] ans) {
    for (final int child : tree[node]) {
      if (child == parent)
        continue;
      postorder(tree, child, node, count, ans);
      count[node] += count[child];
      ans[node] += ans[child] + count[child];
    }
  }

  private void preorder(Set<Integer>[] tree, int node, int parent, int[] count, int[] ans) {
    for (final int child : tree[node]) {
      if (child == parent)
        continue;
      // count[child] nodes are 1 step closer from child than parent
      // (N - count[child]) nodes are 1 step farther from child than parent
      ans[child] = ans[node] - count[child] + (tree.length - count[child]);
      preorder(tree, child, node, count, ans);
    }
  }
}
			

class Solution:
  def sumOfDistancesInTree(self, N: int, edges: List[List[int]]) -> List[int]:
    ans = [0] * N
    count = [1] * N
    tree = defaultdict(set)

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

    def postorder(node, parent=None):
      for child in tree[node]:
        if child == parent:
          continue
        postorder(child, node)
        count[node] += count[child]
        ans[node] += ans[child] + count[child]

    def preorder(node, parent=None):
      for child in tree[node]:
        if child == parent:
          continue
        # count[child] nodes are 1 step closer from child than parent
        # (N - count[child]) nodes are 1 step farther from child than parent
        ans[child] = ans[node] - count[child] + (N - count[child])
        preorder(child, node)

    postorder(0)
    preorder(0)
    return ans