2017-12-09 17 views
1

을 기반으로 트리에서 선택된 객체를 가져온다.이 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; 
    } 

enter image description here

은 내가 어떤 얻을 int입니다 이미 다음 코드를 사용하여 최대 부서의 대답은, 대답은 .. 등등 사람 개체의 목록이 마이너스 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)이라고 말하게됩니다. List 내에서 파란색 상자 인 Person 객체를 모두 가져와야합니다. 2를 입력하면 목록 내의 모든 객체를 가져와야합니다. 붉은 색 보에서 x 및 int 인수에 따라 등등. 어떻게해야합니까? 감사의 도움.

답변

0

이 하나의 작품!

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; 
    } 
1

사람을 메서드의 매개 변수로 전달하는 대신 Person 클래스의 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; 
    } 
} 
+0

가 작동하지 않습니다 - 비어 반환으로> \t getPersonLevel이 작동하지 않습니다 – jimagic

+0

미안 해요, 난 즉시, 내가 코드를 테스트 할 수있는 시간을 갖지 않았 음을 썼다. 내 대답을 편집,이 버전은 테스트를 거쳤습니다 그리고 나는 그것이 작동 보장 할 수 있습니다! –