介绍一下数据库分页
https://www.nowcoder.com/questionTerminal/3577280c810546658f06f19c01ff0345
给定一棵树,求出这棵树的直径,即两个节点距离的最大值。
应该是左右子树遍历深度之和,广度优先搜索+深度优先搜索
注意输入输出。。。。。
public class Solution {
/**
* 树的直径
* @param n int整型 树的节点个数
* @param Tree_edge Interval类一维数组 树的边
* @param Edge_value int整型一维数组 边的权值
* @return int整型
*/
public int solve (int n, Interval[] Tree_edge, int[] Edge_value) {
// write code here
if(Tree_edge == null || Edge_value == null || Tree_edge.length != Edge_value.length){return 0;}
Map<Integer, List<Edge>> graph = new HashMap<>();
int len = Tree_edge.length;
for(int i = 0; i < len; ++i){
Interval inter = Tree_edge[i];
int start = inter.start;
int end = inter.end;
int w = Edge_value[i];
Edge e1 = new Edge(end, w);
if(!graph.containsKey(start)){
List<Edge> temp = new ArrayList<>();
graph.put(start, temp);
}
graph.get(start).add(e1);
Edge e2 = new Edge(start, w);
if(!graph.containsKey(end)){
List<Edge> temp = new ArrayList<>();
graph.put(end, temp);
}
graph.get(end).add(e2);
}
int[] remote = {0, 0}; // remote[0] 代表以0为起点的最长路径长度, remote[1]代表最长路径的终点
dfs(graph, 0, -1, 0, remote);
int[] res = {0, 0};
dfs(graph, remote[1], -1, 0, res);
return res[0];
}
private class Edge{
int end;
int w;
Edge(int end, int w){
this.end = end;
this.w = w;
}
}
private void dfs(Map<Integer, List<Edge>> graph, int from, int prev, int path, int[] res){
List<Edge> edges = graph.get(from);
for(Edge edge: edges){
if(edge.end != prev){
path += edge.w;
if(path > res[0]){
res[0] = path;
res[1] = edge.end;
}
dfs(graph, edge.end, from, path, res);
path -= edge.w; // 回溯
}
}
}
}