【发布时间】: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