forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sum-of-distances-in-tree.cpp
51 lines (46 loc) · 1.5 KB
/
sum-of-distances-in-tree.cpp
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
45
46
47
48
49
50
51
// Time: O(n)
// Space: O(n)
class Solution {
public:
vector<int> sumOfDistancesInTree(int N, vector<vector<int>>& edges) {
unordered_map<int, vector<int>> graph;
for (const auto& edge : edges) {
graph[edge[0]].emplace_back(edge[1]);
graph[edge[1]].emplace_back(edge[0]);
}
vector<int> count(N, 1);
vector<int> result(N, 0);
dfs(graph, 0, -1, &count, &result);
dfs2(graph, 0, -1, &count, &result);
return result;
}
private:
void dfs(const unordered_map<int, vector<int>>& graph,
int node, int parent,
vector<int> *count, vector<int> *result) {
if (!graph.count(node)) {
return;
}
for (const auto& nei : graph.at(node)) {
if (nei != parent) {
dfs(graph, nei, node, count, result);
(*count)[node] += (*count)[nei];
(*result)[node] += (*result)[nei] + (*count)[nei];
}
}
}
void dfs2(const unordered_map<int, vector<int>>& graph,
int node, int parent,
vector<int> *count, vector<int> *result) {
if (!graph.count(node)) {
return;
}
for (const auto& nei : graph.at(node)) {
if (nei != parent) {
(*result)[nei] = (*result)[node] - (*count)[nei] +
count->size() - (*count)[nei];
dfs2(graph, nei, node, count, result);
}
}
}
};