0

Let's assume I have this input

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 

and this class

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

What is the best way to parse this output and then serialize it to json?

What I really need is the algorithm to traverse this input and make a multi-leaf tree structure so I could serialize to json and then pass it to d3js javascript library which will visualize this tree.

Đrakenus
  • 540
  • 3
  • 20
  • This may help: http://stackoverflow.com/questions/11868192/what-collection-to-store-a-tree-structure – NoChance Nov 10 '14 at 22:41

1 Answers1

0

Pseudo code, let me know if you need more:

// 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;
}
Steve Lillis
  • 3,263
  • 5
  • 22
  • 41