2

If I have a TreeView (myTreeview),how can I obtain a list of all the nodes that are parent nodes? i.e. nodes that have children

TK.
  • 46,577
  • 46
  • 119
  • 147
  • The way you use the term "root nodes" is not the way the term is usually used in computer science. More details: http://en.wikipedia.org/wiki/Tree_(data_structure) – Kjetil Watnedal Feb 18 '09 at 11:49
  • As Kjetil said, "root nodes" is not the right term. Try using "leaf nodes". – Leandro López Feb 18 '09 at 12:05
  • The only reason I use the term 'Root Node' is because, this is the term used in c# to add nodes to a treeview. Thanks for the correction 'parent node' should be used instead. – TK. Feb 18 '09 at 12:49

2 Answers2

5

myTreeview.Nodes will give you a list of root nodes as defined by MS which basically means nodes on the root branch of the tree.

This code will build a list of root nodes with children:

    IList<TreeNode> nodesWithChildren = new List<TreeNode>();
    foreach( TreeNode node in myTreeview.Nodes )
        if( node.Nodes.Count > 0 ) nodesWithChildren.Add( node );

Update: and if you wanted all nodes in the TreeView that had a child regardless of how deep into the tree then use a bit of recursion, e.g.

private static IList<TreeNode> BuildParentNodeList(TreeView treeView)
{
    IList<TreeNode> nodesWithChildren = new List<TreeNode>();

    foreach( TreeNode node in treeView.Nodes  )
        AddParentNodes(nodesWithChildren, node);

    return nodesWithChildren;
}

private static void AddParentNodes(IList<TreeNode> nodesWithChildren, TreeNode parentNode)
{
    if (parentNode.Nodes.Count > 0)
    {
        nodesWithChildren.Add( parentNode );
        foreach( TreeNode node in parentNode.Nodes )
            AddParentNodes( nodesWithChildren, node );
    }
}

Update 2: Recursion method with only 1 foreach loop:

private static IList<TreeNode> BuildParentNodeList(TreeView treeView)
{
    IList<TreeNode> nodesWithChildren = new List<TreeNode>();
    AddParentNodes( nodesWithChildren, treeView.Nodes );
    return nodesWithChildren;
}

private static void AddParentNodes(IList<TreeNode> nodesWithChildren, TreeNodeCollection parentNodes )
{
    foreach (TreeNode node in parentNodes)
    {
        if (node.Nodes.Count > 0)
        {
            nodesWithChildren.Add( node );
            AddParentNodes(nodesWithChildren, node.Nodes);
        }
    }
}
ng5000
  • 12,330
  • 10
  • 51
  • 64
1
private void AddNonLeafNodes(List<TreeNode> nonLeafNodes, TreeNodeCollection nodes)
{
    foreach( TreeNode node in nodes )
    {
        if( node.Nodes.Count > 0 )
        {
            nonLeafNodes.Add(node);
            AddNonLeafNodes(nonLeafNodes,node.Nodes);
        }
    }
}

List<TreeNode> nonLeafNodes = new List<TreeNode>();
AddNonLeafNodes(nonLeafNodes,treeView1.Nodes);
user17541
  • 139
  • 1
  • 2
  • 6