559. N 叉树的最大深度

image.png
image.png

递归解法

  1. public class Solution {
  2. public int maxDepth(Node root) {
  3. if (root == null) return 0;
  4. return recursion(root, 1);
  5. }
  6. // 递归计算树的最大深度
  7. public int recursion(Node node, int depth) {
  8. // 如果不为空,递归累加子树
  9. if (node != null) {
  10. // 存放当前节点子树的深度
  11. List<Integer> list = new ArrayList<>();
  12. // 遍历子节点
  13. for (Node child : node.children) {
  14. // 递归计算子树,并加入数组
  15. list.add(recursion(child, depth + 1));
  16. }
  17. // 如果 list 不为空,说明当前节点有子节点,返回最大深度
  18. if (!list.isEmpty()) return Collections.max(list);
  19. }
  20. return depth;
  21. }
  22. }