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.
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
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
}
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) {
//...
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With