Find the maximum number of nested lists

I have an object of class Person

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

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

nested maximum quantity

Each person has a list of all employees inside, and each person has a list of people underneath. How to find the maximum depth? for example, in this image, the maximum depth is 2. second in height is 1. Any rating is appreciated.

+4
source share
4 answers

Actually the original answer was 1+, since I have to subtract minus 1 each time. Here is the correct answer

public int maxDepth() {
        int maxChildrenDepth = 0;

        if(people.size()==0)
            return 0;

        for (Person prs: people) {
            maxChildrenDepth = Math.max(maxChildrenDepth, prs.maxDepth());
        }

        return 1 + maxChildrenDepth;
    }
+1
source

Simply:

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

. node.

1  procedure DFS(G,v):
2      label v as discovered
3      for all edges from v to w in G.adjacentEdges(v) do
4          if vertex w is not labeled as discovered then
5              recursively call DFS(G,w)

.

0

I think that one of the ways (this method may not be the most efficient and the best) could create a while loop with a recursive call to a method that checks if getPeople() returns null. If this is not the case, you can increment the counter and call this check method again recursively. This method should break if it getPeople()returns nulland should return the value assigned to the counter.

0
source

Source: https://habr.com/ru/post/1690496/


All Articles