2

I have the following tree

A
+-B
+-C 
| +-D
+-E
  +-F
  +-G

I am trying to find G given A

private TreeListNode FindTreeNode(TreeListNode node, Enumerations.ItemType type,
                                  Nullable<long> id)
{
    TreeListNode found = null;
    foreach (TreeListNode child in node.Nodes)
    {
        if ((Enumerations.ItemType)child[2] == type)
        {
            if (id == null)
            {
                found = child;
                break;
            }
            else
            {
                if ((long)child[0] == (long)id)
                {
                    found = child;
                    break;
                }
            }
        }
        else
        {
            if (child.HasChildren)
            {
                found = FindTreeNode(child, type, id);
                break;
            }
        }
    }
    return found;
}
FindTreeNode(root,C,null)

Since C comes before G the routinue works for finding C and its children. if the else block if(child.HasChildren) it finds C and its children. When I am trying to find E and its children, the recursive call isn't working correctly. It comes in with the root node A but after it enters the recursion child becomes C and then nodes.Nodes = 1

When I searching for F or G it has to continue its recursion. So how do I set the child to be the root node

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
user575219
  • 2,346
  • 15
  • 54
  • 105
  • possible duplicate of [TreeView search](http://stackoverflow.com/questions/11530643/treeview-search) – MethodMan Apr 15 '14 at 18:41
  • What does your `TreeListNode` look like? And why are you passing `C` as your second argument to `FindTreeNode`? From the signature it should be a `Enumerations.ItemType` – Matt Burland Apr 15 '14 at 18:43

1 Answers1

5

You break even if the recursive call hasn't found anything. Change the relevant code to:

if (child.HasChildren)
{
    found = FindTreeNode(child, type, id);
    if (found != null) 
        break;
}

Your method looks really complicated. Wouldn't this just do the same?

private TreeListNode FindTreeNode(TreeListNode node, Enumerations.ItemType type,
                                  Nullable<long> id)
{
    foreach (TreeListNode child in node.Nodes) {
        if ((Enumerations.ItemType)child[2] == type &&
            (id == null || (long)child[0] == id.Value)) {

            return child;
        }

        if (child.HasChildren) {
            TreeListNode found = FindTreeNode(child, type, id);
            if (found != null) {
                return found;
            }
        }
    }
    return null;
}
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188