如何编写此递归函数以查找对象的最大深度?

alimac83

我正在尝试编写一个将遍历我的对象并返回该对象的水平深度的函数。

例如,如果我在此对象上运行该函数:

var test = {
  name: 'item 1',
  children: [{
    name: 'level 1 item',
    children: [{
      name: 'level 2 item'
    },
    {
      name: 'second level 2 item',
      children: [{
        name: 'level 3 item'
      }]
    }]
  }]
}

var depth = myFunction(test); // Would return 2 (0 index based) as the collection goes 3 levels deep

我一直在尝试编写一个确定最大深度的递归函数,但到目前为止我还做不到。到目前为止,这就是我所拥有的:https : //jsfiddle.net/6cc6kdaw/2/

似乎返回的值是每个节点命中的计数,而不是唯一级别。我知道我要去哪里错了(从某种意义上说,我没有将其过滤掉),但是我已经盯着代码很久了,以至于没有任何意义了!

有人能指出我要去哪里了吗?谢谢

格莱布·科斯特(Gleb Kost)

我对您的代码进行了一些更改,使其可以正常工作:

function getDepth(node, depth = 0) {
    if (!!node.children && node.children.length > 0) {
        var childDepths = [];
        depth++;

        for (var i = 0; i < node.children.length; i++) {
            childDepths.push(getDepth(node.children[i]));
        }
        return depth + Math.max(...childDepths);
    }

    return depth;
}

var depth = getDepth(root);

console.log('currentMaxDepth', depth);
console.log('root', root);

诀窍是在同一个级别上测量兄弟姐妹的深度,而不是选择最深的兄弟姐妹。这也是一个jsfiddle:https ://jsfiddle.net/2xk7zn00/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章