F4NT0 / My-LeetCode-Solvings

C# Code Challenges Solved on LeetCode
https://f4nt0.github.io/My-LeetCode-Solvings/
GNU General Public License v3.0
0 stars 0 forks source link

834. Sum of Distances in Tree #27

Open F4NT0 opened 2 months ago

F4NT0 commented 2 months ago

There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.

You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.

Example 1

image

Example 2

image

Example 3

image

Constraints:

F4NT0 commented 2 months ago
using System;
using System.Collections.Generic;

public class Solution {
    public int[] SumOfDistancesInTree(int n, int[][] edges) {
        int[] ans = new int[n];
        int[] count = new int[n];
        HashSet<int>[] tree = new HashSet<int>[n];

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

        foreach (int[] edge in edges) {
            int u = edge[0];
            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(HashSet<int>[] tree, int node, int parent, int[] count, int[] ans) {
        foreach (int child in 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(HashSet<int>[] tree, int node, int parent, int[] count, int[] ans) {
        foreach (int child in tree[node]) {
            if (child == parent)
                continue;
            ans[child] = ans[node] - count[child] + (tree.Length - count[child]);
            Preorder(tree, child, node, count, ans);
        }
    }
}