I have a problem with a task, I have to count the highest level in a structure which looks like this:
let node = {
age: 23,
name: "christian",
children: [{
age: 25,
name: "michael",
children: [{
age: 33,
name: "Johann",
children: [{
age: 45,
name: "Christiaaann",
}]
}]
}, {
age: 90,
name: "Monika",
children: [{
age: 10,
name: "WHATEVER",
}]
}]
};
The level of the first subtree would be 3 as it contains 3 nested children arrays. The right level would be 2 as it contains 2 nested children arrays.
I tried to solve it recursively, and of course I know that I have to count the level of each subtree and then check it with a condition if it is greater than the previous maximum.
My problem is that I don't know where to count it up in the recursive call.
This is my solution, so far
let node = {
age: 23,
name: "christian",
children: [{
age: 25,
name: "michael",
children: [{
age: 33,
name: "Johann",
children: [{
age: 45,
name: "Christiaaann",
}]
}]
}, {
age: 90,
name: "Monika",
children: [{
age: 10,
name: "WHATEVER",
}]
}]
};
let level_count;
let max_count = 0;
function level_counter(obj, func) {
level_count = 0;
func(obj);
console.log("INSIDEFUNCTION", level_count);
if (obj.children) {
level_count++;
obj.children.forEach(function(child) {
console.log(child);
level_counter(child, func);
});
if (level_count > max_count) {
max_count = level_count;
}
}
}
function tree_get_levels(root) {
level_counter(root, function(obj) { });
console.log("DOWNONE", level_count);
return 0;
}
let result = tree_get_levels(node);
console.log(result);