- 559.N叉树的最大深度
- 题目描述
- 思路
- dfs递归
- Python实现
- Java实现
559.N叉树的最大深度 题目描述
N叉树的最大深度
思路 dfs递归
每个节点的最大深度由它所有子结点的最大深度的最大值决定。
Python实现"""
# 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:
return max(self.maxDepth(child) for child in root.children) + 1 if root and root.children else int(root != None)
Java实现
class Solution {
public int maxDepth(Node root) {
if (root == null) return 0;
int ans = 0;
for (Node child: root.children) {
ans = Math.max(ans, maxDepth(child));
}
return ans + 1;
}
}



