# 【LeetCode】559. Maximum Depth of N-ary Tree 解题报告（Python）

900 篇文章 136 订阅
1033 篇文章 43 订阅

id： fuxuemingzhu

## 题目描述

Given a n-ary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

For example, given a 3-ary tree:

We should return its max depth, which is 3.

Note:

1. The depth of the tree is at most 1000.
2. The total number of nodes is at most 5000.

N叉树的高度。

## 解题方法

### DFS

"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
if not root:
return 0
if not root.children:
return 1
depth = 1 + max(self.maxDepth(child) for child in root.children)
return depth


### BFS

"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
if not root: return 0
depth = 0
que = collections.deque()
que.append(root)
while que:
size = len(que)
for i in range(size):
node = que.popleft()
for child in node.children:
que.append(child)
depth += 1
return depth


## 日期

2018 年 7 月 12 日 —— 天阴阴地潮潮，已经连着两天这样了
2018 年 11 月 6 日 —— 腰酸背痛要废了

01-06 6099
11-19 1507
11-01 97
07-28 1920
07-24 740
08-03 921
07-25 697

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。