题目要求
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
题目分析及思路
题目给出一个N叉树,要求得到它的最大深度。该最大深度为根结点到最远叶结点的结点数。可以使用递归,遍历孩子结点。
python代码
"""
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution:
扫描二维码关注公众号,回复:
5148059 查看本文章
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
if not root:
return 0
elif not root.children:
return 1
else:
c = []
for child in root.children:
c.append(self.maxDepth(child))
c.sort()
return 1 + c[-1]