LeetCode 559. Maximum Depth of N-ary Tree

559. Maximum Depth of N-ary Tree(N叉树的最大深度)

题目:

  给定一个 N 叉树,找到其最大深度。

  最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。

  例如,给定一个 3叉树 :

  

  我们应返回其最大深度,3。

  说明:

    1.   树的深度不会超过 1000
    2.   树的节点总不会超过 5000

思路:

  这题只需要遍历即可,如果结点为null,高度不变,结点存在子节点,进入子节点遍历,借助max函数比较得到最大值即可。

代码:

1     public int maxDepth(Node root) {
2         if(root == null)
3             return 0;
4         int max = 0;
5         for(Node n : root.children)
6             max = Math.max(max,maxDepth(n));
7         return max+1 ;
8     }
View Code
原文地址:https://www.cnblogs.com/blogxjc/p/10966126.html