Practice/Google/Leetcode 1522. Diameter of N-Ary Tree
CodingMust
You are given the root of an N-ary tree where each node can have any number of children. Your task is to find the diameter of the tree.
The diameter of a tree is defined as the length of the longest path between any two nodes in the tree. This path may or may not pass through the root. The length of a path is measured by the number of edges between nodes, not the number of nodes.
An N-ary tree is represented using a Node class where each node contains:
val: an integer valuechildren: a list of child nodes (can be empty)Example 1:
`
Input:
1
/ |
2 3 4
/ |
5 6
Output: 3 Explanation: The longest path is 5 -> 2 -> 1 -> 4 -> 6, which has 4 nodes and 3 edges. `
Example 2:
` Input: 1 | 2 | 3
Output: 2 Explanation: The path goes from 1 -> 2 -> 3, which contains 2 edges. `
Example 3:
`
Input:
1
/ |
2 3 4
Output: 2 Explanation: The longest path connects any two leaf nodes through the root (e.g., 2 -> 1 -> 4), which is 2 edges. `