解法题目描述:
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。
示例 :
输入:root = [1,null,3,2,4,null,5,6]
输出:3
提示:
- 树的深度不会超过 1000 。
- 树的节点数目位于 [0, 104] 之间。
递归即可。
代码"""
# 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
max_dep = 0
for ch in root.children:
max_dep = max(max_dep, self.maxDepth(ch))
return 1 + max_dep
测试结果
说明执行用时:44 ms, 在所有 Python3 提交中击败了 73.39% 的用户
内存消耗:16.6 MB, 在所有 Python3 提交中击败了 86.25% 的用户
算法题来源:力扣(LeetCode)



