| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.SumOfDistancesInTree; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class SumOfDistancesInTreeDepthFirstSearch : ISumOfDistancesInTree |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="n"></param> |
| | 22 | | /// <param name="edges"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int[] SumOfDistancesInTree(int n, int[][] edges) |
| 3 | 25 | | { |
| 3 | 26 | | var graph = new List<int>[n]; |
| | 27 | |
|
| 24 | 28 | | for (var i = 0; i < n; i++) |
| 9 | 29 | | { |
| 9 | 30 | | graph[i] = []; |
| 9 | 31 | | } |
| | 32 | |
|
| 21 | 33 | | foreach (var edge in edges) |
| 6 | 34 | | { |
| 12 | 35 | | int u = edge[0], v = edge[1]; |
| | 36 | |
|
| 6 | 37 | | graph[u].Add(v); |
| 6 | 38 | | graph[v].Add(u); |
| 6 | 39 | | } |
| | 40 | |
|
| 3 | 41 | | var count = new int[n]; |
| 3 | 42 | | var ans = new int[n]; |
| | 43 | |
|
| 3 | 44 | | Dfs(0, -1, graph, count, ans); |
| | 45 | |
|
| 3 | 46 | | Dfs2(0, -1, graph, count, ans); |
| | 47 | |
|
| 3 | 48 | | return ans; |
| 3 | 49 | | } |
| | 50 | |
|
| | 51 | | private static void Dfs(int node, int parent, List<int>[] graph, int[] count, int[] ans) |
| 9 | 52 | | { |
| 9 | 53 | | count[node] = 1; |
| | 54 | |
|
| 51 | 55 | | foreach (var child in graph[node].Where(child => child != parent)) |
| 6 | 56 | | { |
| 6 | 57 | | Dfs(child, node, graph, count, ans); |
| | 58 | |
|
| 6 | 59 | | count[node] += count[child]; |
| 6 | 60 | | ans[node] += ans[child] + count[child]; |
| 6 | 61 | | } |
| 9 | 62 | | } |
| | 63 | |
|
| | 64 | | private static void Dfs2(int node, int parent, List<int>[] graph, int[] count, int[] ans) |
| 9 | 65 | | { |
| 51 | 66 | | foreach (var child in graph[node].Where(child => child != parent)) |
| 6 | 67 | | { |
| 6 | 68 | | ans[child] = ans[node] - count[child] + count.Length - count[child]; |
| | 69 | |
|
| 6 | 70 | | Dfs2(child, node, graph, count, ans); |
| 6 | 71 | | } |
| 9 | 72 | | } |
| | 73 | | } |