559.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实现
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
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;
}
}