LeetCode559. Maximum Depth of N-ary Tree

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode559. Maximum Depth of N-ary Tree相关的知识,希望对你有一定的参考价值。

?????????root   maximum   alt   span   roo   ??????   ??????   pen   nod   

???????????????????????????????????????????????????????????????????????????????????????????????????

?????????????????????????????????????????????????????????????????????

?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

 

?????????????????????

"""
# 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
        """
        if not root:
            return 0
        if not root.children:
            return 1
        sub_max=[]
        for child in root.children:
            sub_max.append(self.maxDepth(child)+1) 
        return max(sub_max)

???????????????

   1.???list????????????None??????[ ]?????????????????? if not list

   2.list ??????????????????append

  3.list?????????max

 

 

???????????????

class Solution(object):
    def maxDepth(self, root):
        """
        :type root: Node
        :rtype: int
        """
        if not root:
            return 0
        if not root.children:
            return 1
        depth = 1 + max(self.maxDepth(child) for child in root.children)
        return depth

????????????list????????????

 

"""
# 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
        """
        if not root: return 0
        depth = 0
        que = collections.deque()
        que.append(root)
        while que:
            size = len(que)
            for i in range(size):
                node = que.popleft()
                for child in node.children:
                    que.append(child)
            depth += 1
        return depth

??????????????????

??????????????????????????????????????????

 

 

??????????????????

 

以上是关于LeetCode559. Maximum Depth of N-ary Tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode559. Maximum Depth of N-ary Tree

[LeetCode&Python] Problem 559. Maximum Depth of N-ary Tree

Leetcode 559. Maximum Depth of N-ary Tree

559. Maximum Depth of N-ary Tree

559. Maximum Depth of N-ary Tree

559. N 叉树的最大深度简单