以更简单的方式获取树数据结构的深度

时间:2019-03-14 14:26:29

标签: javascript json typescript recursion

我有以下格式的JS对象类似JSON的层次结构:

[
  {
    subs: [ ...other objects... ]
  },
  ...other objects...
]

我写了一个方法,可以返回这种层次结构的级别数:

/* Returns the depth of the tree. */
public getDepth(): number {

  function f(obj: object): number {
    let depth = 0;
    if (obj['subs'].length > 0) {
      obj['subs'].forEach((s: object) => {
        const tempDepth = f(s);
        if (tempDepth > depth) depth = tempDepth;
      });
    }
    return depth + 1;
  }

  if (this.tree.length > 0)
    return Math.max(...this.tree.map((s: object) => f(s)));
  else return 0;

}

它可以工作,但是太复杂了。然后,我发现了以下更简洁的代码:https://stackoverflow.com/a/16075976/5214911

唯一的区别是我没有一个基础对象,而是一个对象数组作为根。如何简化代码以节省多余的if和迭代次数?

示例数据:

const data1 = []; // depth: 0

const data2 = [{}, {}, {}]; // depth: 1

const data3 = [{}, // depth: 5
  {
    "subs": [{
      "subs": [{
        "subs": [{}]
      }, {
        "subs": [{
          "subs": [{}]
        }]
      }]
    }, {
      "subs": [{
        "subs": [{}]
      }]
    }]
  },
  {}
];

2 个答案:

答案 0 :(得分:3)

您可以绘制每个孩子的深度并取其最大值。

function getDepth(array) {
    return 1 + Math.max(0, ...array.map(({ subs = [] }) => getDepth(subs)));
}

const
    data1 = [],
    data2 = [{}, {}, {}],
    data3 = [{}, { subs: [{ subs: [{ subs: [{}] }, { subs: [{ subs: [{}] }] }] }, { subs: [{ subs: [{}] }] }] }, {}];

console.log(getDepth(data1) - 1); // 0
console.log(getDepth(data2) - 1); // 1
console.log(getDepth(data3) - 1); // 5

答案 1 :(得分:2)

使用Array.prototype.map()将数组的每个项目更改为其长度,然后在数组上使用Math.max()

getDepth = function (obj) {
    var depth = 0;
    if (obj.children) {
        obj.children.forEach(function (d) {
            var tmpDepth = getDepth(d)
            if (tmpDepth > depth) {
                depth = tmpDepth
            }
        })
    }
    return 1 + depth
}
let arr = [...];
let depths = arr.map(x => getDepth(x))
let maxDepth = Math.max(...depths)