I have a TreeView
Control with set of nodes and child nodes. For example:
ROOT has A,B,C.
A has a1, a2, a3 and then
The following code is used for traversing a TreeView's nodes and returning only the leaf nodes:
private IEnumerable<TreeNode> LeafNodes(TreeNode root)
{
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.Push(root);
while (stack.Count > 0)
{
TreeNode current = stack.Pop();
if (current.Nodes.Count == 0)
{
yield return current;
}
else
{
foreach (TreeNode child in current.Nodes)
{
stack.Push(child);
}
}
}
}
I use it for accessing the filenames in an explorer-like TreeView:
private void LogFileNames()
{
//There may be more than one node at root level
foreach (TreeNode rootNode in FileTreeView.Nodes)
{
//Print only filenames, not directories
foreach (TreeNode leafNode in LeafNodes(rootNode))
{
Logger.Info(leafNode.Text);
}
}
}