在idea实现
树的直径
http://www.nowcoder.com/questionTerminal/a77b4f3d84bf4a7891519ffee9376df3
package medium;
import com.sun.source.tree.Tree;
import java.util.*;
class Interval {
int start;
int end;
}
public class TreeOfDiam {
public static void main(String[] args) { Interval[] Tree_edge = new Interval[5]; for(int i = 0; i < Tree_edge.length;i++){ Tree_edge[i] = new Interval(); } Tree_edge[0].start = 0; Tree_edge[0].end = 1; Tree_edge[1].start = 1; Tree_edge[1].end = 5; Tree_edge[2].start = 1; Tree_edge[2].end = 2; Tree_edge[3].start = 2; Tree_edge[3].end = 3; Tree_edge[4].start = 2; Tree_edge[4].end = 4; int Edge_value[] = {3,4,2,1,5} ; solve(6,Tree_edge,Edge_value); } public static int[][] get_graph(int n,Interval[] Tree_edge,int[] Edge_value){ int[][] graph = new int[n][n]; for(int i = 0;i < n;i++){ for(int j = 0;j < n;j++){ if(i == j) graph[i][j] = 0; else graph[i][j] = 9999; } } for(int i = 0;i < Edge_value.length;i++){ graph[Tree_edge[i].start][Tree_edge[i].end] = Edge_value[i]; graph[Tree_edge[i].end][Tree_edge[i].start] = Edge_value[i]; } return graph; } public static int solve (int n, Interval[] Tree_edge, int[] Edge_value) { // write code here int graph[][] = get_graph(n,Tree_edge,Edge_value); int[] distance = new int[n]; for(int i = 0;i < n;i++){ distance[i] = graph[0][i]; } int[] flag = new int[n]; flag[0] = 1; for(int i = 1;i < n;i++){ int max = 0; int v = 0; for(int j = 1;j < n;j++){ if(flag[j] == 0 && graph[i][j] > max && graph[i][j] != 9999 ){ max = graph[i][j]; v = j; } } flag[v] = 1; for(int k = 1;k < n;k++){ if(distance[k] < distance[v] + graph[v][k] && graph[v][k] != 9999){ distance[k] = distance[v] + graph[v][k]; //System.out.println(distance[k]); } } } Arrays.sort(distance); System.out.println(distance[n - 1] - 9999); return distance[n - 1]; }
}