title: Using a global variable versus passing a variable around while writing a recursive algorithm
body: <p>I have a method to flatten a Binary search tree. I have two approaches for it:</p>
  
  <p>• Using a variable and passing it around</p>
  
  <pre><code>import java.util.*;
  
  public class BST {
  
  private Node root;
  
  private class Node {
      private int val;             // associated data
      private Node left, right;  // left and right subtree
  
      public Node(int val) {
          this.val = val;
  
      }
  }   
  
  public ArrayList&lt;Integer&gt; flattenTree(){
  
      ArrayList&lt;Integer&gt; list = new ArrayList&lt;&gt;();
      flattenTree(root, list);
  
      return list;
  }
  
  public void flattenTree(Node node, ArrayList&lt;Integer&gt; list)
  {
  
      if (node == null)
          return;
  
      flattenTree(node.left, list);
      list.add(node.val);
      flattenTree(node.right, list);
  
  }    
  
  public static void main(String[] args) {
  
      BST bst = new BST();
  
      bst.add(5);
      bst.add(1);
      bst.add(0);
      bst.add(3);
  
      System.out.println(bst.flattenTree());
  
  }
  
  }
  </code></pre>
  
  <p>• Using a class variable:</p>
  
  <pre><code>import java.util.*;
  
  public class BST {
  
  private Node root;
  
  ArrayList&lt;Integer&gt; list = new ArrayList&lt;&gt;();    
  
  private class Node {
      private int val;             // associated data
      private Node left, right;  // left and right subtree
  
      public Node(int val) {
          this.val = val;
  
      }
  }   
  
  public ArrayList&lt;Integer&gt; flattenTree(){
  
      flattenTree(root);
  
      return list;
  }
  
  public void flattenTree(Node node)
  {
  
      if (node == null)
          return;
  
      flattenTree(node.left);
      list.add(node.val);
      flattenTree(node.right);
  
  }    
  
  public static void main(String[] args) {
  
      BST bst = new BST();
  
      bst.add(5);
      bst.add(3);
      bst.add(1);
      bst.add(0);
      bst.add(3);
      bst.add(3);
  
      bst.printInorder();
      System.out.println(bst.flattenTree());
  
  }
  </code></pre>
  
  <p>}</p>
  
  <p>In both cases I get:</p>
  
  <pre><code>sgupta$ java BST
  [0, 1, 3, 5]
  </code></pre>
  
  <p>I'm a beginner to java (high school) and wondering what the pros and cons of each approach are. </p>
  
  <p>The only one I can think of is that approach #2 has less messy code by not having to pass the list around.</p>