【问题标题】:Assign parent and children to Node将父节点和子节点分配给节点
【发布时间】:2014-11-10 22:37:00
【问题描述】:

假设我有这个输入

0       //1st zero
  1     //is child of 1st zero
0       //2nd zero
  1     //is child of 2nd zero
  1     //is child of 2nd zero
    2   //is child of 2nd one
    2   //is child of 2nd one
  1     //etc...
    2 
      3
    2
  1 
0 

还有这个类

public class Node
{
    public int Number { get; set; }
    public Node Parent { get; set; }
    public List<Node> Children { get; set; }
}

解析此输出然后将其序列化为 json 的最佳方法是什么?

我真正需要的是遍历此输入并制作多叶树结构的算法,以便我可以序列化为 json,然后将其传递给 d3js javascript 库,该库将可视化这棵树。

【问题讨论】:

标签: c# algorithm tree


【解决方案1】:

伪代码,如果您需要更多,请告诉我:

// Added to Node class:
public int GetDepthRecursive()
{
    return Parent == null ? 0 : (Parent.GetDepthRecursive() + 1);
}

// To parse the text file into a node tree:
Node rootNode = new Node { Number = 0 }; // You need a node for all those zero nodes to hang off
Node currentNode = rootNode;
foreach (var row in rows)
{
    rowDepth = row.StartingSpaces.Count(); // Use any method you want to count these spaces
    var rowNode = new Node { Number = int.Parse(row) };

    // The new row node is at the same or lower depth than us
    // Go back up the tree to find the right parent for it
    while (currentNode.GetDepthRecursive() > rowDepth)
    {
        currentNode = currentNode.Parent;
    }

    rowNode.Parent = currentNode;
    currentNode = rowNode;
}

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多