LeetCode 559 Maximum Depth of N-ary Tree 解题报告

时间:2023-03-09 17:44:13
LeetCode 559 Maximum Depth of N-ary Tree 解题报告

题目要求

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:

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]