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:

扫描二维码关注公众号,回复: 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]

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10351508.html