Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a variable local

Tags:

java

I made this recursive method that calculates the longest path in a binary tree. the path its store in an arralist and then returned. however, i had to declare the array list variable global. is it possible to make this method but his the array list variable being 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 a recursive program and every time it call itself it will create a new array list object variable with difference address if you know what i mean.

like image 571
Lexy Feito Avatar asked Mar 21 '13 16:03

Lexy Feito


4 Answers

Pass the arraylist in the method parameters:

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

Then when you do the recursive call:

longestPath(root.right, path);

Just pass a new Arraylist() when you call the method initially

like image 79
cowls Avatar answered Oct 10 '22 04:10

cowls


What you should do is have your main function create an ArrayList and pass it into a helper function that does all the work; e.g:

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
}
like image 21
JohnMcG Avatar answered Oct 10 '22 05:10

JohnMcG


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

    public static <T> ArrayList<T> longestPath(BinaryNode<T> root, ArrayList path) {
    //...
like image 39
Igor Avatar answered Oct 10 '22 05:10

Igor


if you pass the 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;

 } 
like image 26
s_bei Avatar answered Oct 10 '22 03:10

s_bei