Reputation: 4151
I have class that can have nested same class instances:
class SomeClass
{
List<SomeClass> SomeClasses;
}
And... I need to know what is the most high amount in chain Parent - Children
.
I so confused about this, so I don't even know how to start doing it. Most likely it can't be done without recursion.
Upvotes: 1
Views: 44
Reputation:
Given that any SomeClass instance forms a tree, perhaps you are looking for the depth of the tree. If that's the case, you would indeed use recursion: write a function that accepts a SomeClass
and returns 1 plus the maximum of the list formed by applying itself to the SomeClasses
list.
Here for example is an implementation in JS:
const depth = ({ things }) => 1 + Math.max(0, ...things.map(depth))
depth({
things: [
{
things: [
{
things: []
},
{
things: [
{
things: []
}
]
}
]
}
]
});
// 4
Upvotes: 2