方法一:广度优先搜索(BFS)
"""
# 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 not root:
return 0
que = [root]
ans = 0
while que:
for _ in range(len(que)):
node = que.pop(0)
for child in node.children:
que.append(child)
ans += 1
return ans
方法二:深度优先搜索(DFS)
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root:
return 0
maxChildDepth = 0
for child in root.children:
childDepth = self.maxDepth(child)
maxChildDepth = max(maxChildDepth, childDepth)
return maxChildDepth + 1
深度优先搜索-更简洁写法
class Solution:
def maxDepth(self, root: 'Node') -> int:
return max((self.maxDepth(child) for child in root.children), default=0) + 1 if root else 0