[leetcode] 559. Maximum Depth of N-ary Tree @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/87882971

原题

https://leetcode.com/problems/maximum-depth-of-n-ary-tree/

解法

递归. Base case是当节点为空或者节点为叶子节点时, 分别返回0和1.

代码

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""
class Solution(object):
    def maxDepth(self, root):
        """
        :type root: Node
        :rtype: int
        """
        # base case
        if not root: return 0
        if not root.children:
            return 1
        return 1 + max([self.maxDepth(node) for node in root.children])

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/87882971
今日推荐