目录结构
1.题目
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
例如,给定一个 3叉树
:
我们应返回其最大深度,3。
说明:
- 树的深度不会超过
1000
。 - 树的节点总不会超过
5000
。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
递归。
参考二叉树求最大深度。
public class Solution559 {
@Test
public void test559() {
Node n5 = new Node(5);
Node n6 = new Node(6);
List<Node> l3 = Arrays.asList(n5, n6);
Node n2 = new Node(3, l3);
Node n3 = new Node(2);
Node n4 = new Node(4);
List<Node> l2 = Arrays.asList(n2, n3, n4);
Node root = new Node(1, l2);
System.out.println(maxDepth(root));
}
public int maxDepth(Node root) {
int max = 0;
if (root == null) {
return 0;
}
if (root.children != null && root.children.size() > 0) {
max = maxDepth(root.children.get(0));
for (int i = 1; i < root.children.size(); i++) {
{
max = Math.max(max, maxDepth(root.children.get(i)));
}
}
}
return max + 1;
}
}
- 时间复杂度:
- 空间复杂度: