559 N叉树的最大深度
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。
输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:5
"""
# 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:
# 非递归
# results = []
# if not root:return 0
# from collections import deque
# que = deque([root])
# while que:
# result = []
# n = len(que)
# for _ in range(n):
# node = que.popleft()
# result.append(node.val)
# for i in node.children:
# que.append(i)
# results.append(result)
# return len(results)
# 递归
res = []
if not root:return 0
def helper(root, depth):
if len(res) == depth:res.append([])
res[depth].append(root.val)
for i in root.children:
helper(i, depth+1)
helper(root, 0)
return len(res)