Using a global variable versus passing a variable around when writing a recursive algorithm

I have a way to smooth a binary search tree. I have two approaches to this:

• Using a variable and passing it around

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<Integer> flattenTree(){

    ArrayList<Integer> list = new ArrayList<>();
    flattenTree(root, list);

    return list;
}

public void flattenTree(Node node, ArrayList<Integer> 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());

}

}

• Using a class variable:

import java.util.*;

public class BST {

private Node root;

ArrayList<Integer> list = new ArrayList<>();    

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<Integer> 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());

}

}

In both cases, I get:

sgupta$ java BST
[0, 1, 3, 5]

I am new to java (high school) and wondering what are the pros and cons of each approach.

The only thing I can think of is that approach # 2 has less dirty code since it doesn't need to skip the list.

+4
source share
3 answers

To add @caskey to the paragraphs, I would like to point out two other main advantages of the first version of the code.

-, , , . ,

  • , ,
  • , ,
  • , ,
  • , .

- , , , , . , .

-, . " ". " list ". , , . , , , .

, !

+3

, , .

1) , (.. ).

2) , .

- .

+2

:

  • , ?
  • , (.. )?
  • Can you escape the state by passing arguments in a method call, which simplifies code verification.
0
source

All Articles