Leetcode 1245 Tree Diameter
- diameter: the number of edges in a longest path in that tree
- bidirectional edge
Depth of the Tree solution
Using ArrayList
LinkedList<Integer>[] adjacencyList = new LinkedList[n];
避免bidirectional edge 导致的问题,node的读取方向是一致的。node有两种读取方式,分别是是作为出发点和终点。
private int depth(int root, int parent, LinkedList<Integer>[] adjacencyList) {
for (int child : adjacencyList[root]) {
if (child != parent) { // Only one way from root node to child node, don't allow child node go to root node again!
}
}
}
For node A which has multi-child-nodes.
The longest diameter of node A is (maxDepth1st + maxDepth2nd +1).
The longest path may or may not contain root node.
DFS Solution - Memoization
Using Map
DFS Solution - Memoization