【leetcode系列】【算法】【简单】N叉树的最大深度

题目:

题目链接:https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/

解题思路:

dfs,遍历每个节点的N个字数,并查找最大高度

代码实现:

"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution:
    def maxDepth(self, root: 'Node') -> int:
        res = 0
        def dfs(root):
            if not root:
                return 0
            
            depth = [0]
            for child in root.children:
                depth.append(dfs(child))
                
            return max(depth) + 1
        
        return dfs(root)
发布了138 篇原创文章 · 获赞 13 · 访问量 2460

猜你喜欢

转载自blog.csdn.net/songyuwen0808/article/details/105590828