c# - Algorithm to iterate TreeView nodes in reverese from the last leaf to root -
what best algorithm iterate winforms treeview control last leafs roots in reverse? c#
the code below visit each node , traverse completely, depth-first, until comes leaf. then, unwinds stack, call dosomethingwithnode
each node. depth
parameter there show nodes returned in reverse order.
void reversetraverse(treenodecollection nodes, int depth) { if (nodes == null) return; foreach (treenode child in nodes) { reversetraverse(child.nodes, depth+1); dosomethingwithnode(child, depth); } }
to call it, assuming mytreeview
treeview
instance:
reversetraverse(mytreeview.nodes, 1);
note doesn't give deepest leaf nodes first, rather makes sure leaf node output before parent node. if tree looks this:
node 1 node 1.1 node 1.2 node 1.2.1 node 2 node 2.1 node 2.1.1 node 2.1.1.1 node 2.1.2
the output order be:
node 1.1 node 1.2.1 node 1.2 node 1 node 2.1.1.1 node 2.1.1 node 2.1.2 node 2.1 node 2
if want deepest nodes first (i.e. node 2.1.1.1 output first), you'd have make full traversal (in forward order easiest) , build list of nodes corresponding depths. sort list depth (descending) , output in order.
Comments
Post a Comment