我如何编写这个递归函数来找到我的对象的最大深度? [英] How do I write this recursive function to find the max depth of my object?

查看:29
本文介绍了我如何编写这个递归函数来找到我的对象的最大深度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数将遍历我的对象并返回该对象的级别深度.

例如,如果我在这个对象上运行函数:

var test = {name: '项目 1',孩子们: [{name: '级别 1 项目',孩子们: [{name: '2 级物品'},{name: '二级 2 项',孩子们: [{name: '3 级物品'}]}]}]}var depth = myFunction(test);//当集合深入 3 层时将返回 2(基于 0 索引)

我一直在尝试编写一个确定最大深度的递归函数,但到目前为止我无法正确完成.这是我到目前为止所拥有的:https://jsfiddle.net/6cc6kdaw/2/>

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

谁能指出我哪里出错了?谢谢

解决方案

我对您的代码进行了一些更改,使其按您希望的方式工作:

function getDepth(node, depth = 0) {如果 (!!node.children && node.children.length > 0) {var childDepths = [];深度++;for (var i = 0; i < node.children.length; i++) {childDepths.push(getDepth(node.children[i]));}返回深度 + Math.max(...childDepths);}返回深度;}var depth = getDepth(root);console.log('currentMaxDepth', depth);console.log('root', root);

诀窍是测量同一级别兄弟姐妹的深度,然后选择其中最深的.这里还有一个 jsfiddle:https://jsfiddle.net/2xk7zn00/

I'm trying to write a function that will loop through my object and return the level depth of the object.

For example, if I ran the function on this object:

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

I've been trying to write a recursive function that determines the maximum depth but so far I can't get it right. This is what I have so far: https://jsfiddle.net/6cc6kdaw/2/

It seems the value returned is a count of every node hit, not unique levels. I understand where I'm going wrong (in the sense that I'm not filtering this out) but I'm at the point where I've been staring at the code for so long that nothing's making sense any more!

Anyone able to point out where I'm going wrong? Thanks

解决方案

I have changed your code a bit to work as you want it to:

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);

The trick is to measure depths of siblings on the same level and than pick the deepest of them. Here's also a jsfiddle: https://jsfiddle.net/2xk7zn00/

这篇关于我如何编写这个递归函数来找到我的对象的最大深度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆