将方法转换为递归

时间:2019-03-21 18:24:40

标签: java recursion methods

我想在ponzi计划中查看我下面的用户总数。

这是有效的硬编码方法,我想使其递归

public int getAllChildrenFromDown(List<Credential> children) {
    if (!(children.size() == 0)) {
        for (Credential child : children) {
            count = count + 1;
            List<Credential> grandChildren = credentialRepository.findByParentId(child.getParentId());
            if (!(grandChildren.size() == 0)) {
                for (Credential grandChild : grandChildren) {
                    count = count + 1;
                    List<Credential> greatGrandChildren = credentialRepository.findByParentId(grandChild.getParentId());
                    if (!(greatGrandChildren.size() == 0)) {
                        for (Credential greatGrandChild : greatGrandChildren) {
                            count = count + 1;
                            List <Credential> greatGreatGrandChildren =credentialRepository.findByParentId(greatGrandChild.getParentId());
                            if(!(greatGreatGrandChildren.size()==0)) {
                                for (Credential greatGreatGr: greatGreatGrandChildren) {
                                    count=count +1;
                                }
                            }
                        }
                    }
                }

            }
        }
    }
    return count;
}

下面是我尝试过的方法,但是我遇到了无限循环

public int getAllChildrenFromDown(List<Credential> children) {

    if (!(children.size() == 0)) {
        for (Credential child : children) {
            count = count + 1;
            List<Credential> grandChildren = credentialRepository.findByParentId(child.getParentId());
            getAllChildrenFromDown(grandChildren);

        }
    }
    return count;
}

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

正如@doelleri所说,上述解决方案是 credentialRepository.findByParentId(child.getId());

而不是 credentialRepository.findByParentId(child.getParentId());