2017-12-09 14 views
1

だから私はこのPersonオブジェクトを持っています。一人一人が私すでに次のコードを使用して最大のdept答えは、答えは私が得る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; 
    } 

何でもある人物オブジェクトのリストを持っているので、..に

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

私は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のメソッドを作成してみませんか?

あなたが持っているでしょう結果:この1作品

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

申し訳ありませんが、私はその場で、私はコードをテストするための時間を取らなかったことを書きました。私は私の答えを編集しました、このバージョンはテストされており、私はそれが動作することを保証することができます! –

関連する問題