title: Find the path from leaf to root in Tree
body: <p>I saw a lot of examples about Trees and how to recursively search them, but not like my case. So I decide to ask. </p>
  
  <p>How can I find a path from any leaf to the root?</p>
  
  <p>My problem is that I have a lot of child nodes per parent. Here is an example of my code: </p>
  
  <pre><code> private LinkedList&lt;TreeNode&gt; findPath(LinkedList&lt;TreeNode&gt; path, TreeNode root, TreeNode leaf){
      if(root == null || root.name==null) return null;
  
      path.add(root);
  
      if(root.name.equals(leaf.name))
          return path;
  
      //Check if the leaf that we are looking for is one of the root children
      if(root.children==null) return null;
      for(TreeNode children : root.children){
          if(children.name.equals(leaf.name)){
              path.add(children);
              return path;
          }
      }
      //Search in all the childrens of the root recursively
      for(TreeNode children : root.children){
          LinkedList&lt;TreeNode&gt; result =  findPath(path, children, leaf);
          if(result != null)
              return result;
      }
  
      //The leaf is not found. 
      return null;
  }
  </code></pre>
  
  <p>And the problem is that every time when I check a child, if I don't find my leaf there I take back but I have add the child node in the path and my path becomes very big. </p>