Untitled
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 } }
Leave a Comment