recursion ?

S

Steve

I'm surprised that I'm having trouble with this, I have done this before...
anyway, I'm trying to locate a TreeNode in a TreeView wqith a recursive
function, here is the code
<code>
private TreeNode RecursivelyFindNodeByTag(TreeNode node, Object data)
{
if(node.Tag == data)
{
return node;
}

foreach(TreeNode n in node.Nodes)
{
if(n.Tag == data)
{
return n;
}
RecursivelyFindNodeByTag(n, data);
}
return null;
}
</code>

I pass the TopNode to the initial call to RecursivelyFindNodeByTag
It find the node, but the stack still needs to unwind it's calls, as is it
does, it returns null. I'm after a total block on this, what am I doing
wrong?

Thanks for taking a look,
Steve
 
M

Mattias Sjögren

Steve,
foreach(TreeNode n in node.Nodes)
{
if(n.Tag == data)
{
return n;
}

You don't really need this if since the check will be made by the
recursive call.

RecursivelyFindNodeByTag(n, data);

Should be

return RecursivelyFindNodeByTag(n, data);


Mattias
 
O

Oliver Sturm

Steve wrote:

I'm after a total block on this, what am I doing
wrong?


I guess it should be better like this, from the top of my head:

private TreeNode RecursivelyFindNodeByTag(TreeNode node, Object data) {
if(node.Tag == data)
return node;
foreach(TreeNode n in node.Nodes) {
TreeNode result = RecursivelyFindNodeByTag(n, data);
if (result != null)
return result;
}
return null;
}
 
S

Steve

Thanks all, it was a bug on my part, I had some leftover code that was
getting called that was inserting nodes during the search, so that was
screwing everything up.
Thanks for the help!
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top