Untitled
unknown
plain_text
a year ago
788 B
5
Indexable
import java.util.*;
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int val) {
this.val = val;
this.children = new ArrayList<>();
}
public Node(int val, List<Node> children) {
this.val = val;
this.children = children;
}
}
public class NAryTreeDepth {
// Function to calculate the maximum depth of an N-ary tree
public int maxDepth(Node root) {
if (root == null) return 0; // Base case: empty tree has depth 0
int maxChildDepth = 0;
for (Node child : root.children) {
maxChildDepth = Math.max(maxChildDepth, maxDepth(child));
}
return 1 + maxChildDepth; // Add 1 for the current root
}
}
Editor is loading...
Leave a Comment