Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find max nested list count

I have this class object called Person

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

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

nested max count

Each person have list of all employees inside and that each person has List of people underneath. How to find the max deep? for example, in that image, max deep is 2. second highest is 1. Any help is appreciated.

like image 253
jimagic Avatar asked Jan 30 '23 01:01

jimagic


1 Answers

Simply:

public static int maxDepth(Person p) {
    int maxChildrenDepth = 0;
    for (Person c: p.getPeople()) {
        maxChildrenDepth = Math.max(maxChildrenDepth, maxDepth(c));
    }
    return 1 + maxChildrenDepth;
}
like image 97
Jean Logeart Avatar answered Feb 04 '23 10:02

Jean Logeart