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){
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.
source
share