gpt4 book ai didi

c# - 如何使用 LINQ 从树中的所有节点获取列表?

转载 作者:行者123 更新时间:2023-11-30 20:11:39 24 4
gpt4 key购买 nike

如何使用 LINQ 从树中的所有节点获取列表?

我的类(class)是:

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

public List<Node> Children { get; set;}
}

class Tree
{
public Tree()
{
Roots = new List<Node>();
}

List<Node> Roots { get; set;}
}

最佳答案

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

public IEnumerable<Node> GetSubTree()
{
return Children.SelectMany(c => c.GetSubTree()).Concat(new[] { this });
//Post-order traversal
}

public List<Node> Children { get; set; }
}

class Tree
{
public Tree()
{
Roots = new List<Node>();
}

public IEnumerable<Node> GetAllNodes()
{
return Roots.SelectMany(root => root.GetSubTree());
}

List<Node> Roots { get; set; }
}

一棵树怎么可能有多个根呢?这不是森林吗?

关于c# - 如何使用 LINQ 从树中的所有节点获取列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3458318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com