LeetCode 1245 Tree Diameter
Given an undirected tree, return it’s diameter, which is the number of edges in a longest path in that tree.
the input is int[][] edges, that means the tree has no roots and it’s represents in adjancent matrix.
but we can’t see the tree as graph because tree is graph without cycle, so a tree is a tree and a graph can be a tree but not necessarily, and the problem can be convert to the longest path in a tree(with the weight of each edge is 1)
class Solution {
private int diameter = 0;
public int treeDiameter(int[][] edges) {
//convert int[][] to List<Integer>[]
List<Integer>[] graph = new List[edges.length + 1]; //this is a arraylist with list in it, but why with length of edges.length + 1?
for (int i = 0; i <= edges.length; i++) {
graph[i] = new ArrayList<>();
}
for (int[] e: edges) {
graph[e[0]].add(e[1]);
graph[e[1]].add(e[0]);
}
depth(0, -1, graph); //root level, it's parent level
return diameter;
}
private int depth(int root, int parent, List<Integer>[] graph) { //the max depth of current node
//the core idea of this function is: longest path through a node is sum of top 2 depth of children's tree
int maxDepth1st = 0; //the largest
int maxDepth2nd = 0; //the second largest
for (int child: graph[root]) { //for each child of current root(not root to be precise)
if (child == parent) continue; Only one way from root node to child node, don't allow child node go to root node again!
int childDepth = depth(child, root, graph);
//check whether we need to update the 1st largest and the second largest
if (childDepth > maxDepth1st) {
maxDepth2nd = maxDepth1st;
maxDepth1st = childDepth;
} else if (childDepth > maxDepth2nd) {
maxDepth2nd = childDepth;
}
}
int longestPath = maxDepth1st + maxDepth2nd + 1; //it counts the number of nodes
diameter = Math.max(diameter, longestPath - 1); //maintain a global maximal
return maxDepth1st + 1;
}
}

浙公网安备 33010602011771号