I want to implement a method that will allow me to find a node in a tree. The way I do this recursively uses global variables to know when to stop.
I have a class:
class Node
{
public Node() {
Children = new List<Node>();
}
public List<Node> Children;
public string Name;
public string Content;
}
And the method that I have now:
private bool IsNodeFound = false;
private void Find(Node node, string stringToFind, Action<Node> foundNode)
{
if(IsNodeFound)
return;
if (node.Content.Contains(stringToFind)){
foundNode(node);
IsNodeFound =true;
}
foreach (var child in node.Children)
{
if (child.Content.Contains(stringToFind)){
foundNode(node);
IsNodeFound =true;
}
Find(child, stringToFind, foundNode);
}
}
, and the way I use the Find method looks like this:
// root is a node that contain children and those children also contain children
// root is the "root" of the tree
IsNodeFound =false;
Node nodeToFind = null;
Find(root, "some string to look for", (x)=> nodeToFind=x);
So my question is how can I make this method more elegant. I will like the method signature:
public Node FindNode(Node rootNode);
I think this is redundant, what I'm doing, and probably the best way to create this method. Or perhaps I could modify the node class so that I can achieve the same result with the linq query.
source
share