How to make a local variable

I made this recursive method that computes the longest path in a binary tree. his store's path to an arralist and then returned. however, I had to declare a list variable of the global array. Is it possible to make this method, but its array list variable is local.

public static <T> ArrayList<T> longestPath(BinaryNode<T> root){
    //ArrayList path = new ArrayList();

   if(root == null) return null;

   if(height(root.left) > height(root.right)){
       path.add(root.element);

       longestPath(root.left);


   }else{
       path.add(root.element);

       longestPath(root.right);

   }

   return path;

}

The reason I had to make it global is because its recursive program, and each time it calls itself, will create a new variable of an array list object with a difference address, if you know what I mean.

+5
source share
4 answers

, , ArrayList , ; :

public static ArrayList longestPath(BinaryNode root)
{
    ArrayList path = new ArrayList();
    return longestPathHelper(root, path);
}

private static ArrayList longestPathHelper(BinaryNode root, ArrayList path)
{
    // Existing code, except recursive calls pass path as well
}
+5

arraylist :

public static <T> List<T> longestPath(BinaryNode<T> root, List<T> path){

, :

longestPath(root.right, path);

new Arraylist(),

+11

If you need access to a variable and cannot make it global, another option is to pass it as a parameter:

    public static <T> ArrayList<T> longestPath(BinaryNode<T> root, ArrayList path) {
    //...
+3
source

if you pass an ArrayList to your recursive function yes:

public static <T> ArrayList<T> longestPath(BinaryNode<T> root, ArrayList path){
ArrayList lPath = path;

 if(root == null) return null;

 if(height(root.left) > height(root.right)){
   lPath.add(root.element);

   longestPath(root.left, lPath);


 }else{
   lPath.add(root.element);

   longestPath(root.right, lPath);

 }

 return lPath;

 } 
+3
source

All Articles