Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0 Star 0 Fork 0

徐云天/leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
_834.java 1.68 KB
一键复制 编辑 原始数据 按行查看 历史
徐云天 提交于 2021-06-22 17:47 +08:00 . 增加834
import java.util.*;
public class _834 {
static class Solution1{
public int[] sumOfDistancesInTree(int n, int[][] edges) {
//dfs 2次,
//第一次从0开始,统计res[0],以及count[i];
// if(edges.length == 0) return new int[n];
Map<Integer, Set<Integer>> graph = new HashMap<>();
for(int[] edge : edges){
graph.computeIfAbsent(edge[0],k->new HashSet<>()).add(edge[1]);
graph.computeIfAbsent(edge[1],k->new HashSet<>()).add(edge[0]);
}
int[] res = new int[n];
int[] count = new int[n];
System.out.println(graph);
res[0] = computeCurDistanceAndCurCount(graph,count,0,-1,0);
computeRes(graph,count,res,0,-1);
return res;
}
public int computeCurDistanceAndCurCount(Map<Integer,Set<Integer>> graph,int[] count,int cur,int pre,int deep){
count[cur] = 1;
int res = deep;
for(int child : graph.getOrDefault(cur, Collections.emptySet())){
if(child == pre) continue;
res += computeCurDistanceAndCurCount(graph,count,child,cur,deep+1);
count[cur] += count[child];
}
return res;
}
public void computeRes(Map<Integer,Set<Integer>> graph,int[] count,int[] res,int cur,int pre){
// if(pre == cur) return ;
for(int child : graph.getOrDefault(cur,Collections.emptySet())){
if(child == pre) continue;
res[child] = res[cur] + count.length - 2 * count[child];
computeRes(graph,count,res,child,cur);
}
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/xuyuntian/leetcode.git
git@gitee.com:xuyuntian/leetcode.git
xuyuntian
leetcode
leetcode
master