C# How to represent and traverse an N-Ary tree

Viewed 444

tree example

I need a structure to represent an N-ary tree, and then convert it to a JSON, in C#. I am using .net core. I want to be able to traverse the tree of course. I couldn't find anything for representing an N-Ary tree with C#, an N-ary tree it's not a binary tree, which instead, I found a lot of documentation about it.

1 Answers

It seems that you don't need any "special" datastructure - just a class containing a collection of itself:

class HierarchyMember
{
    public string Name { get; set; }
    public List<HierarchyMember> Children { get; set; }
}

And I suppose any popular json serializer for C# should handle that. For example Netonsoft's Json.NET:

Console.WriteLine(JsonConvert.SerializeObject(new HierarchyMember
{
    Name = "Root",
    Children = new List<HierarchyMember>
    {
        new HierarchyMember {Name = "Child_1"}, 
        new HierarchyMember {Name = "Child_2"}
    }
}, Newtonsoft.Json.Formatting.Indented));

Prints:

{
  "Name": "Root",
  "Children": [
    {
      "Name": "Child_1",
      "Children": null
    },
    {
      "Name": "Child_2",
      "Children": null
    }
  ]
}
Related