我怎样才能获得使用LINQ在树中的所有节点的列表?节点、列表、LINQ

由网友(不要生气啦)分享简介:我怎样才能得到一个列表,使用LINQ在树中的所有节点?我的类:类节点{公共类节点(){儿童=新的​​名单,其中,节点>();}公开名单<节点>儿童{获得;组;}}类树{公共树(){根=新的名单,其中,节点>();}名单<节点>根{获得;组;}}解决方案 类节点{公共节点()...

我怎样才能得到一个列表,使用LINQ在树中的所有节点?

我的类:

 类节点
{
 公共类节点()
 {
  儿童=新的​​名单,其中,节点>();
 }

 公开名单<节点>儿童{获得;组;}
}

类树
{
 公共树()
 {
  根=新的名单,其中,节点>();
 }

 名单<节点>根{获得;组;}
}
 

解决方案

 类节点
    {
    公共节点()
    {
        儿童=新的​​名单,其中,节点>();
    }

    公开的IEnumerable<节点> GetSubTree()
    {
        返回Children.SelectMany(C => c.GetSubTree())。CONCAT(新[] {此});
        //后序遍历
    }

    公开名单<节点>儿童{获得;组; }
}

类树
{
    公共树()
    {
        根=新的名单,其中,节点>();
    }

    公开的IEnumerable<节点> GetAllNodes()
    {
        返回Roots.SelectMany(根=> root.GetSubTree());
    }

    名单<节点>根{获得;组; }
}
 

如何才能一棵树有一个以上的根关系吗?这不是一个森林吗?

C Lambda表达式和表达式树 二 表达式树

How can I get a List from all nodes in a tree using LINQ?

My classes are:

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; }
}

How can a tree have more than one root though? Isn't this a forest?

阅读全文

相关推荐

最新文章