题目链接:559. N 叉树的最大深度
解法一
深度优先遍历。递归法遍历 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:
if root is None:
return 0
if root.children is None:
return 1
ans = 0
for child in root.children:
ans = max(ans, self.maxDepth(child))
return ans + 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 is None:
return 0
states, depth = [root], 0
while len(states) > 0:
next_states = []
for node in states:
if node.children is not None:
next_states.extend(node.children)
states, depth = next_states, depth + 1
return depth