559. N 叉树的最大深度
递归解法
public class Solution {
public int maxDepth(Node root) {
if (root == null) return 0;
return recursion(root, 1);
}
// 递归计算树的最大深度
public int recursion(Node node, int depth) {
// 如果不为空,递归累加子树
if (node != null) {
// 存放当前节点子树的深度
List<Integer> list = new ArrayList<>();
// 遍历子节点
for (Node child : node.children) {
// 递归计算子树,并加入数组
list.add(recursion(child, depth + 1));
}
// 如果 list 不为空,说明当前节点有子节点,返回最大深度
if (!list.isEmpty()) return Collections.max(list);
}
return depth;
}
}