title: Need help in returning from a recursive method
body: <p>I am trying to trace the path of a node in a binary tree (not a binary search tree). Given a node, I am trying to print the values of the path from the root.</p>
  
  <p><img src="https://4.bp.blogspot.com/_kRev2kjeMro/S3RMNVO4v4I/AAAAAAAACEg/0jv0ztv1Gfo/s320/Trace+path+in+a+binary+tree.png" alt="alt text"></p>
  
  <p>I have written the following program. </p>
  
  <pre><code>package dsa.tree;
  
  import java.util.Stack;
  
  public class TracePath {
      private Node n1;
  
      public static void main(String args[]){
          TracePath nodeFinder = new TracePath();
          nodeFinder.find();
      }
  
      public void find(){
          Tree t = getSampleTree();
          tracePath(t,n1);
      }
  
      private Tree getSampleTree() {
          Tree bsTree = new BinarySearchTree();
          int randomData[] = {43,887,11,3,8,33,6,0,46,32,78,76,334,45};
          for(int i=0;i&lt;randomData.length;i++){
              bsTree.add(randomData[i]);
          }
          n1 = bsTree.search(76);
          return bsTree;
      }
  
      public void tracePath(Tree t, Node node){
          trace(t,node);
      }
  
      Stack&lt;Node&gt; mainStack = new Stack&lt;Node&gt;();
  
      public void trace(Tree t, Node node){
          trace(t.getRoot(),node);
      }
  
      private void trace(Node parent, Node node){
          mainStack.push(parent);
          if(node.data == parent.data){
              for(Node iNode:mainStack){
                  System.out.println(iNode.data);
              }
              return;
          }
          if(parent.left != null){
              trace(parent.left, node);
          }
          if(parent.right!=null){
              trace(parent.right, node);
          }
          mainStack.pop();
      }
  }
  </code></pre>
  
  <p>I am getting the output properly. But its kind of messy. If you see the method trace(Node, Node), I am printing the values which I should not do. I want the trace method to properly complete. At least, I should kill the recursive structure at the stage i encounter the if condition. </p>
  
  <p>Please advise.</p>