Search code examples
javascriptrecursioncollectionsnestedmax

Return the Maximum Depth of objects in a Nested Collection (JavaScript)


I looking for a suitable algorithm that will return the maximum depth of a collection of objects within a hierarchy of collections. I have a root object which may or may not contain a collection of objects of the same type, of variable number. Each of these child objects, themselves may contain a collection of the same type and variable number, and so-on, down to any depth. (see diagram).

Object hierarchy

I looking for the best algorithm that would return an integer that represents the level of the deepest collection in the hierarchy. (So in my diagram that would be 4.).

I've tried the following function recursively but it is always out by one.

 var getLevelFunc = function (children) {
             var depth = 0
            for (var c = 0; c < children.length; c++) {
                let child= children[c];
                if (child.children() != null && child.children().length > 0) {
                    var tempDepth = getLevelFunc(child.children());
                    if (tempDepth > depth) {
                        depth = tempDepth
                    }
                }
            }
            return 1 + depth;
        }

Many thanks


Solution

  • I'm not 100% sure of the data structure you've got so I mocked a simpler one with out any children() methods, hope it still makes sense though.

    I think that part of what makes your solution a bit trickier is that you start with the children rather than the node, afterall if you have one node with no children it should still have a depth of one (if I've understood things correctly). By passing the depth into the getLevelFunc at each stage I think it probably makes it easier to see what should be going on in the code.

    const tree = {
      name: 'root',
      children: [
        {
          name: 'Child 1',
          children: [
            { name: 'Child 1.1' },
            {
              name: 'Child 1.2',
              children: [
                { name: 'Child 1.2.1' },
                { name: 'Child 1.2.2' },
                { name: 'Child 1.2.3' },
              ]
            }
          ],
        },
        {
          name: 'Child 2',
          children: [
            { name: 'Child 2.1' },
            { name: 'Child 2.2' },
          ],
        },
        { name: 'Child 3' },
      ]
    };
    
    const getLevelFunc = function (node, start_depth = 1) {
      let depth = start_depth;
      
      for (const child of (node.children ?? []))
        depth = Math.max(depth, getLevelFunc(child, start_depth + 1));
      
      return depth;
    };
    
    console.log(getLevelFunc(tree));