题目链接:
力扣https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/aaa
【分析】这道题主要弄清楚叶子结点的判定条件,然后用dfs即可,如果为叶子则返回1,否则递归遍历当前节点的所有儿子,找儿子的最大深度+1就是当前节点的深度。
# 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:
if root == []:
return 0
if root.children == []:
return 1
else:
d = 0
for i in root.children:
d = max(self.maxDepth(i))
return d