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]

        

 

posted on 2019-02-04 10:33  锋上磬音  阅读(114)  评论(0编辑  收藏  举报