有向无环分层图的实现

时间:2019-06-11 10:04:01

标签: javascript algorithm tree

我需要显示一个看起来像这样的无环有向图:

enter image description here

我创建了一个类似于以下内容的嵌套分层数据结构:

[
 {
  node: 'abs'
  children: [
   {
    node: 'jhg',
    children: [{...}]
   {
    node: 'AAA',
    children: [{...}]
   },
 {
  node: 'fer'
  children: [
   {
    node: 'AAA',
    children: [{...}]
   {
    node: 'xcv',
    children: [{...}]
   },
 {
]

我不确定这是否是实际显示数据的最佳方法,因为具有多个父级和子级的节点会出现多次,但是我还不知道如何处理它。

我只是想将那些节点渲染为一个虚构的网格。因此,我需要解析我的数据结构并设置其网格值。问题是我不知道如何使用层次结构逻辑来解析数据结构。

我现在正在做的事情显然会导致具有多个父级的节点出现问题:

for (const root of allRoots) {
  currentLevel = 0;
  if (root.node === 'VB8') {
    getChildrenTree(root);
  }
}

function getChildrenTree(node) {
  currentLevel++;
  node._gridX = currentLevel;

  if (node.children.length > 0) {
    for(const nextChild of children ) {
      getChildrenTree(nextChild);
    }
  }

此代码的问题在于,它将仅通过一条路径运行,然后在没有任何孩子的情况下停止。

我只需要一个遍历树并设置每个节点层次结构级别的算法。

我希望这不要太令人困惑。

1 个答案:

答案 0 :(得分:0)

如果要从两个单独的父对象引用同一节点,则不应多次定义它。我建议列出具有单个“不可见”根节点的平面阵列中的所有节点,并按ID或数组索引引用子代:

[
 {id: 0, name: "root", children: [1, 2]},
 {id: 1, name: "abs", children: [3, 4]},
 {id: 2, name: "fer", children: [5, 6]},
 {id: 3, name: "jhg", children: [...]},
 {id: 4, name: "AAA", children: [...]},
 ...
]

然后您可以像这样递归设置它们的树深度:

function setDepth(node, depth) {
  if (node._gridX && node._gridX >= depth) {
    // node has been visited already through a path of greater or equal length
    // so tree depths wouldn't change
    return
  }
  node._gridX = depth
  node.children
    .map(idx => nodeArray[idx]) // get the actual objects from indices
    .forEach(child => setDepth(child, depth+1))
}
setDepth(nodeArray[0], 0) // start at root

...但是要小心,因为如果您的节点有任何循环,此算法将陷入循环中