根据传递的参数从树中获取选定的对象

Get selected object from the tree based on passing argument

所以我有了这个 Person 对象。每个人都有人物对象列表等等..

public class Person {
    ....
    private List<Person> people = new ArrayList<>();

    ....

    public List<Person> getPeople() {
        return people;
    }

    public void setPeople(List<Person> people) {
        this.people = people;
    }

我已经使用以下代码得到了最大的部门答案,答案是我得到的整数减 1

public static int maxDepth(Person p) {
        int maxChildrenDepth = 0;
        for (Person c: p.getPeople()) {
            maxChildrenDepth = Math.max(maxChildrenDepth, maxDepth(c));
        }
        return 1 + maxChildrenDepth;
    }

所以如果我将 Person 对象和 int 传递给方法,比如说 getPersonLevel(List allPerson, 1) ,我应该得到列表中所有的 Person 对象,它们是蓝色框,如果我输入 2,我应该得到所有红色框中列表中的对象等等,具体取决于 int 参数..我该怎么做?任何帮助欣赏。

与其将人作为方法的参数传递,为什么不制作 class 人的 maxDepthgetPersonLevel 方法?

结果你会得到:

public class Person {

    private Set<Person> people = new HashSet<>();

    public Set<Person> getPeople() {
        return people;
    }

    public void setPeople(Set<Person> people) {
        this.people = people;
    }

    public int maxDepth() {
        int maxChildrenDepth = 0;
        for (Person prs : people) {
            maxChildrenDepth = Math.max(maxChildrenDepth, prs.maxDepth());
        }
        return 1 + maxChildrenDepth;
  }

  public Set<Person> getPersonLevel(int depth) {
      Set<Person> ppl = new HashSet<>();
      ppl.addAll(gatherEmployees(ppl, depth));
      return ppl;
  }

  private Set<Person> gatherEmployees(Set<Person> ppl, int depth) {
      if (depth - 1 > 0 && people != null) {
          people.forEach(prs -> ppl.addAll(prs.gatherEmployees(ppl, depth - 1)));
      }
      return people;
  }
}

这个有效!

public Set<Person> getPersonLevel(Person person, int depth) {
       Set<Person> aList = new HashSet<>();

       if (depth == 1)
           aList.addAll(person.getPeople());

       if (depth > 1){
           for (Person pp : person.getPeople()) {
                   aList.addAll(getPersonLevel(pp, depth -1));
           }
       }
       return aList;
    }