【问题标题】:Directed Acyclic Hierarchical Graph Implementation有向无环层次图实现
【发布时间】:2019-06-11 10:04:01
【问题描述】:

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

我创建了一个类似这样的嵌套分层数据结构:

[
 {
  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);
    }
  }

此代码的问题在于它只会通过一条路径,然后在没有任何子节点时停止。

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

我希望这不会太混乱。

【问题讨论】:

  • getChildrenTree 究竟应该返回什么?
  • 实际上它没有返回任何东西。我现在只是用它来设置 gridX 值。返回不在我的代码中。

标签: javascript algorithm tree


【解决方案1】:

如果您想从两个不同的父节点引用同一个节点,则不应多次定义它。我建议在一个平面数组中列出所有节点,其中包含一个“不可见”根节点,并通过 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

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

【讨论】:

  • 我怀疑这样的事情会更有意义。非常感谢您的意见。我马上试试看。
  • 是的,这绝对按预期工作。非常感谢
猜你喜欢
  • 1970-01-01
  • 2023-03-24
  • 2013-10-03
  • 2015-08-25
  • 1970-01-01
  • 2017-12-20
  • 1970-01-01
  • 2016-04-12
  • 1970-01-01
相关资源
最近更新 更多