HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Searching for nodes in a huge tree

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
nodessearchinghugefortree

Problem

This is supposed to search for a node in a huge Treeview. The node could be found in many places. In other words there may be many nodes and the resulting tree should be expanded depending on where nodes are found.

I was asked to avoid recursivity in this method. The only solution I was able to get is using LINQ queries but I cannot since we are under 2.0 framework.

Can I avoid recursivity in this method?

private void CheckFoundTreeNode(TreeNode startingTreeNode, List parentItems, ItemNode foundItemNode)
    {
        foreach (TreeNode childTreeNode in startingTreeNode.Nodes)
        {
            ItemNode itemNode = TreeBuilder.GetItemNode(childTreeNode);
            Item item = itemNode.Item;

            bool isParent;
            if (item.Ancestor == null)
                isParent = parentItems.Contains(item);
            else
            {
                Item ancestor = ((Grammar)item).DirectAncestor;
                isParent = parentItems.Contains(ancestor);
            }

            if (isParent)
            {
                childTreeNode.Expand();
                CheckFoundTreeNode(childTreeNode, parentItems, foundItemNode);
            }

            else if (itemNode == foundItemNode)
            {
                startingTreeNode.Expand();
                m_ListOfFoundNodes.Add(childTreeNode);
            }
        }
    }

Solution

The simplest way to avoid the recursive traversal is to have two lists: nodes you want to visit and nodes you have visited. Your loop then goes like this:

  • take a node from the 'to visit' list, or end if empty



  • check the node



  • add any connected nodes that aren't in the 'visited' list to the 'to visit' list

Context

StackExchange Code Review Q#78417, answer score: 4

Revisions (0)

No revisions yet.