c# - Prune tree branches where ending nodes meet some criteria -


i have treenode class follows:

public class treenode {     public enum nodetype { root,element, category}     public treenode()     {         children = new list<treenode>();     }     public list<treenode> children { get; set; }     public string name { get; set; }     public nodetype type { get; set; } } 

and have buildtree method populates tree structure setting node name , type each node (e.g. first node set root type, , child nodes either element or category types).

i'm looking efficient way (perhaps using linq) prune tree branches ending node type not of type category. ideas on how achieve that?

here visual example:

before:

root | |_ nodea (element) |_ node b (element) |  |_ node b.1 (category) |_ node c (element) |  |_ node c.1 (element) |    |_node c.1.1 (category) |_ node d (element)    |_node d.1 (element) 

after:

root | |_ node b (element) |  |_ node b.1 (category) |_ node c (element)    |_ node c.1 (element)      |_node c.1.1 (category) 

thanks in advance!

first need describe how depth first aggregation of tree:

//seed: leafnode -> accumulate //func: interiornode, children accumulates -> accumulate public static taccumulate aggregate<taccumulate>(     treenode root,     func<treenode, taccumulate> seed,     func<treenode, list<taccumulate>, taccumulate> func) {     if (root.children == null || !root.children.any())         return seed(root);     return func(root, children.select(child => child.aggregate(seed, func)).tolist()); } 

then can use make modification such 1 requested:

tree.aggregate(     leaf => new     {         keep = leaf.nodetype == treenode.nodetype.category,         node = leaf     },     (node, children) =>     {         var removal = new hashset<treenode>(             children.where(child => !child.keep).select(child => child.node));         node.children.removeall(removal.contains);         return new         {            keep = children.any(child => child.keep),            node = node         };     }); 

this gives concise, declarative way describe transform want applied tree without getting details of traversal in description of transform.


Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -