Diameter of N-Ary Tree — LeetCode 1522 Python Solution
MediumLeetCode PremiumTreeDepth-First Search
- Problem
- #1522
- Pattern
- Tree Traversal
- Reading time
- 6 min
- Source
- leetcode.com
The problem
Given a root of an N-ary tree, you need to compute the length of the diameter of the tree. The diameter of an N-ary tree is the length of the longest path between any two nodes in the tree.
Example
- Input
- root = [1,null,3,2,4,null,5,6]
- Output
- 3
- Explanation
- Diameter is shown in red color.
Python solution
Python
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children if children is not None else []
"""
class Solution:
def diameter(self, root: 'Node') -> int:
"""
:type root: 'Node'
:rtype: int
"""
def dfs(root):
if root is None:
return 0
nonlocal ans
m1 = m2 = 0
for child in root.children:
t = dfs(child)
if t > m1:
m2, m1 = m1, t
elif t > m2:
m2 = t
ans = max(ans, m1 + m2)
return 1 + m1
ans = 0
dfs(root)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1522. Diameter of N-Ary Tree is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1522. Diameter of N-Ary Tree?
- LeetCode 1522. Diameter of N-Ary Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1522. Diameter of N-Ary Tree?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 1522. Diameter of N-Ary Tree?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 1522. Diameter of N-Ary Tree cover?
- LeetCode 1522. Diameter of N-Ary Tree is tagged Tree and Depth-First Search on LeetCode.
- Is LeetCode 1522. Diameter of N-Ary Tree a premium problem?
- Yes. LeetCode 1522. Diameter of N-Ary Tree is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.