title: Find node when traversing tree
body: <p>I want to implement a method that will enable me to find a node in a tree. The way I do it is recursively using global variables to know when to stop. </p>
  
  <p><strong>I have the class:</strong></p>
  
  <pre><code>class Node    // represents a node in the tree
  { 
       // constructor
       public Node() {
            Children = new List&lt;Node&gt;();
       }
  
       public List&lt;Node&gt; Children; 
       public string Name;
       public string Content;            
  }
  </code></pre>
  
  <p><strong>And the method I have right now is:</strong></p>
  
  <pre><code>    private bool IsNodeFound = false; // global variable that I use to decide when to stop
  
      // method to find a particular node in the tree
      private void Find(Node node, string stringToFind, Action&lt;Node&gt; 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);
          }
  
      }
  </code></pre>
  
  <p><strong>and the way I use the Find method is like:</strong></p>
  
  <pre><code>   // 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)=&gt; nodeToFind=x);
  </code></pre>
  
  <p><strong>So my question is</strong> how can I make this method more elegant. I will like the signature of the method to look like:</p>
  
  <pre><code>   public Node FindNode(Node rootNode);
  </code></pre>
  
  <p>I think it is to redundant what am I doing and there is probably a better way of creating that method. Or perhaps I could alter the Node class so that I can achieve the same thing with a linq query.</p>