C#如何表示和遍历一棵N叉树

标签 c# json tree

tree example

我需要一个结构来表示 N 叉树,然后在 C# 中将其转换为 JSON。我正在使用 .net 核心。我当然希望能够遍历树。 我找不到用 C# 表示 N 元树的任何内容,N 元树不是二叉树,相反,我找到了很多关于它的文档。

最佳答案

似乎您不需要任何“特殊”数据结构——只需要一个包含自身集合的类:

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

而且我想任何流行的 C# json 序列化程序都应该处理这个问题。例如 Netonsoft 的 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));

打印:

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

关于C#如何表示和遍历一棵N叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63736938/

相关文章:

c# - GraphicsPath 和 DrawPath - 删除相交线

c# - 在 UWP Windows 10 中找不到位图类

php - MySQL JSON 存储与两个表

algorithm - 如何在 O(nlgn) 中检查二叉树是否为 BST?

go - 如何在for循环中使用两个initStmt?

c# - iOS 不支持全局 PushAsync,请使用 NavigationPage

c# - 如何使用 Checkbox 的 C# 显示 DataGridView 列

c# - 具有 "self-creating"属性的对象的自定义 JSON 序列化以无限循环结束

ios - 是否可以将 Realm 对象序列化为 JSON?

python - 从 Pandas /字典创建交互式层次结构图