The code below will visit each node and completely cross it, first in depth, until it reaches the leaf. Then, when it unwinds the stack, DoSomethingWithNode is called for each node. The depth parameter should show you that the nodes are returned in the 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 is an instance of TreeView :
ReverseTraverse(MyTreeView.Nodes, 1);
Note that this at first does not give you the deepest leaf nodes, but rather ensures that any leaf node is displayed before its parent node. If your tree looks like 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 will 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 you want to have the deepest nodes first (i.e. node 2.1.1.1 will be the first), then you will have to make a full round (in the direct order it will be easier) and build a list of nodes with their corresponding depths. Then sort the list by depth (descending) and display in order.
source share