Untitled

 avatar
unknown
plain_text
a month ago
1.9 kB
1
Indexable
// Definition for a Node in N-ary tree
class Node {
    public int val;
    public List<Node> children;
    
    public Node() {
        children = new ArrayList<>();
    }
    
    public Node(int _val) {
        val = _val;
        children = new ArrayList<>();
    }
}

class Solution {
    // Variable to track the maximum diameter found so far
    private int maxDiameter = 0;
    
    public int diameter(Node root) {
        // Handle empty tree case
        if (root == null) return 0;
        
        // Calculate height and update diameter
        calculateHeight(root);
        
        // Return the maximum diameter found
        return maxDiameter;
    }
    
    // Helper method to calculate height and update diameter
    private int calculateHeight(Node node) {
        if (node == null) return 0;
        
        // Keep track of the two highest paths from children
        int maxHeight1 = 0;  // Highest path
        int maxHeight2 = 0;  // Second highest path
        
        // Process all children
        for (Node child : node.children) {
            // Get height of current child subtree
            int currentHeight = calculateHeight(child);
            
            // Update the two maximum heights
            if (currentHeight > maxHeight1) {
                maxHeight2 = maxHeight1;
                maxHeight1 = currentHeight;
            } else if (currentHeight > maxHeight2) {
                maxHeight2 = currentHeight;
            }
        }
        
        // Update maxDiameter if path through current node is longer
        // Path length = height1 + height2 (edges through current node)
        maxDiameter = Math.max(maxDiameter, maxHeight1 + maxHeight2);
        
        // Return height of current subtree
        // Add 1 for the edge connecting to parent
        return maxHeight1 + 1;
    }
}
Leave a Comment