1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
sum-of-distances-in-tree.cpp 1.50 KB
一键复制 编辑 原始数据 按行查看 历史
// 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);
}
}
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助