Java 对象包含对象的列表。查找最大深度
我有以下课程:Java 对象包含对象的列表。查找最大深度,java,Java,我有以下课程: class A { List<A> as; } 我需要返回3 我尝试了递归方法,递归深度计算: public static int computeDepth(A a) { int maxDepth = 0; for(A innerA : a.getAs()) { int depth = computeDepth(innerA); if(depth > maxDepth) m
class A {
List<A> as;
}
我需要返回3
我尝试了递归方法,递归深度计算:
public static int computeDepth(A a)
{
int maxDepth = 0;
for(A innerA : a.getAs())
{
int depth = computeDepth(innerA);
if(depth > maxDepth)
maxDepth = depth;
}
return maxDepth + 1;
}
使用Java 8流:
class A {
List<A> as;
public int getDepth() {
return 1 + as.stream().mapToInt(A::getDepth).max().orElse(0);
}
}
你能展示你已经尝试过的吗?你需要说明
secondA.add(firstA)代码>?在类A中设置静态变量max_Size=3。在addA方法中,检查大小是否等于或大于max_Size(如果大于max_Size),然后替换或删除,或者执行任何您想要的操作to@bradimus不。不会有这种情况。我不能向类添加方法,但我知道如何使用它。现在我要试着了解这个想法。谢谢你,伙计。如果这不是a的方法,我会加上一个解释。
class A {
List<A> as;
public int getDepth() {
return 1 + as.stream().mapToInt(A::getDepth).max().orElse(0);
}
}
public class MyClass {
public static int getDepth(A a) {
return 1 + a.as.stream().mapToInt(MyClass::getDepth).max().orElse(0);
}
}