我做了这个递归方法,计算二叉树中最长的路径.它的存储路径在一个集会上然后返回.但是,我不得不声明数组列表变量全局.是否有可能使这个方法,但他的数组列表变量是本地的.
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;
}
Run Code Online (Sandbox Code Playgroud)
我必须使它成为全局的原因是因为它是一个递归程序,每次它调用自身它将创建一个具有差异地址的新数组列表对象变量,如果你知道我的意思.
java ×1