1. 程式人生 > >559. N叉樹的最大深度(簡單、樹)

559. N叉樹的最大深度(簡單、樹)

給定一個 N 叉樹,找到其最大深度。最大深度是指從根節點到最遠葉子節點的最長路徑上的節點總數。

方法一:簡單的,就是自身遞迴,前提要明白children是子樹節點的集合,應該遍歷輸出計算

"""
# 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
        deep = 1 + max(self.maxDepth(child) for child in root.children)
        return deep

執行用時: 132 ms, 在Maximum Depth of N-ary Tree的Python提交中擊敗了61.93% 的使用者

方法二:稍微麻煩一點的,但是可以學習新的東西,就是N叉樹的層次遍歷。這裡層次遍歷樹,每一層加一個一就可以了

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

執行用時: 128 ms, 在Maximum Depth of N-ary Tree的Python提交中擊敗了96.49% 的使用者