using System.Collections.Generic;
public string Type { get; set; }
public Node Parent { get; set; }
public List<Node> Children { get; set; }
public string DisplayTree(int level) =>
$"{(string.Join(string.Empty, Enumerable.Repeat("\t", level)))}- {Type}\n{(Children != null ? string.Join(string.Empty, Children.Select(child => child.DisplayTree(level + 1))) : string.Empty)}";
public static class Helpers
public static IEnumerable<Node> BuildTreeWithLeafNodes(this IEnumerable<Node> topNodes, Func<Node, bool> leafNodeCondition)
.Select(topNode => topNode.GetSubTreeWithLeafNodes(leafNodeCondition))
.Where(subTree => subTree != null);
public static Node GetSubTreeWithLeafNodes(this Node node, Func<Node, bool> leafNodeCondition)
if (node.Children != null && node.Children.Any())
node.Children = node.Children
.BuildTreeWithLeafNodes(leafNodeCondition)
if (node.Children != null && node.Children.Any())
return leafNodeCondition(node) ? node : null;
public static void Main()
new Node { Type = "N1" },
new Node { Type = "N3" },
new Node { Type = "N3" },
new Node { Type = "N1" },
Console.WriteLine("Tree:\n-----");
foreach (var topNode in tree)
Console.WriteLine(topNode.DisplayTree(0));
var filteredTree = tree.BuildTreeWithLeafNodes(node => node.Type == "N1");
Console.WriteLine("Filtered tree:\n-----");
foreach (var topNode in filteredTree)
Console.WriteLine(topNode.DisplayTree(0));