Consider the following tree structure:
-root
|
|
|-child1
|
|-innerChild1
|
|-innerChild2
|
|-child2
I am looking to create a JavaScript function that can determine the depth of an element within the tree. For example:
var depth = getInnerDepth(root);
depth = 3;
In this case, the depth is 3. The root has a parent at depth 1, first degree children at depth 2, and one child (child1) with children at depth 3.
var depth = getInnerDepth(child1);
depth = 2;
The depth here is 2 because child1 is considered the parent, so its depth is 1. Child1 has children, hence the result being 2.
var depth = getInnerDepth(innerChild1);
depth = 1;
For innerChild1, the depth is 1 as it does not have any children from its perspective.
It seems like this should be implemented recursively, but I am struggling to find the best approach.
function getInnerDepth(parent){
var depth = 1;
if (parent.hasChildren) {
depth++;
parent.children.forEach(function(child){ getInnerDepth(child); })
}
return depth;
}
This pseudo code illustrates the general idea, although it's not functional yet.