LeetCode 1522 Diameter of N-ary Tree
Base question: LC543 diameter of binary tree, LC1245 tree diameter.
diameter of binary tree are solved using recursion, we use a global max, and we get the maxdepth of left and maxdepth of right subtree, and we always maintain this global maximal.
tree diameter, now, this tree is very much like a graph, but it’s still a tree, it’s very much like this N-ary tree. so what’s the difference between them? the input.
the input of that tree diameter is int[][] edges, it has no root, it can be start from any node.
the input of this N-ary diameter is Node root.
there are some similarity between this code and that tree diameter, pay attention to that.
class Solution {
private int diameter = 0;
public int diameter(Node root) {
height(root);
return diameter;
}
private int height(Node node) { //the maximum height based on current node as root
if (node.children.size() == 0) return 0;
int maxHeight1st = 0;
int maxHeight2nd = 0;
for (Node child: node.children) {
int parentHeight = height(child) + 1; //the height of parent of current child node
if (parentHeight > maxHeight1st) {
maxHeight2nd = maxHeight1st;
maxHeight1st = parentHeight;
} else if (parentHeight > maxHeight2nd) {
maxHeight2nd = parentHeight;
}
int distance = maxHeight1st + maxHeight2nd; //the number of edges on this route
diameter = Math.max(diameter, distance);
}
return maxHeight1st;
}
}

浙公网安备 33010602011771号