C#递归排序

时间:2018-10-14 19:36:27

标签: c# sorting recursion

我有一个这样的数据结构:

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

   public Something() {
     Children = new List<Something>();
   }
 }

示例数据:

    var one = new Something();
    one.Name = "B";

    var two = new Something();
    two.Name = "A";

    var three = new Something();
    three.Name = "C";

    one.Children.Add(new Something { Name = "F"});
    one.Children.Add(new Something { Name = "E"});
    one.Children.Add(new Something { Name = "D"});

    three.Children.Add(new Something { Name = "F"});
    three.Children.Add(new Something { Name = "E"});
    three.Children.Add(new Something { Name = "D"});

    var data = new List<Something>();
    data.Add(one);
    data.Add(two);
    data.Add(three);

我需要一个函数来对所有级别的字段进行排序。树的深度任意的

到目前为止,我已经拥有了:

public static List<Something> SortTree(List<Something> node) {
  if (node == null) {
    return null;
  }

  return node
    .OrderBy(x => x.Name)
    .Select(y => {
       if (y.Children.Count() > 0) {
         var t = y.Children;
         SortTree(t.ToList());
       }

       return y;
    })
    .ToList();
  }

调用SortTree(data)会返回仅对父级进行排序的数据。

感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

您所在的行

SortTree(t.ToList());

由于您从未真正更新Children字段,因此直接丢弃结果。

您可能想要类似的东西

y.Children = SortTree(y.Children.ToList());

尽管我会尝试将您的SortTree()更改为不返回值的方法。

答案 1 :(得分:2)

如果您有一个带有循环的 mesh (不仅仅是一个 tree )(child是其自身的父级),您将遇到 recoursion < / em>。另一个可能的问题(相同的堆栈溢出)是图形太深(“树的深度是任意”)。我建议对 BFS 进行一些修改 算法

public static List<Something> SortTree(List<Something> node) {
  Queue<List<Something>> agenda = new Queue<List<Something>>();

  agenda.Enqueue(node);

  HashSet<List<Something>> alreadySorted = new HashSet<List<Something>>() { null };

  while (agenda.Any()) {
    var current = agenda.Dequeue();

    if (alreadySorted.Add(current)) {
      current.Sort((left, right) => string.Compare(left.Name, right.Name));

      foreach (var child in current)
        agenda.Enqueue(child.Children);
    }
  }

  return node;
}

答案 2 :(得分:0)

如果您想进行递归操作,就不会无所事事地编写自己的循环。至少就我所知(远未完成),您不能继续使用linq。您必须自己编写排序循环。

至此,递归调用“ SortTree(current);”。变得不重要