allpaths是在findPaths(...)方法中定义的List>,该方法在其范围内调用dfs(...)方法,但是我不明白为什么allpaths不是全局变量,所以为什么要对其进行更新? 那么,调用dfs方法后allpaths List如何更新?
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
};
class FindAllTreePaths {
public static List> findPaths(TreeNode root, int sum) {
List> allpaths = new ArrayList>();
List cpath = new ArrayList();
dfs(root, sum, cpath, allpaths);
return allpaths;
}
private static void dfs(TreeNode root, int sum, List cpath, List> result){
if(root == null){
return;
}
if(root.val == sum && root.left == null && root.right == null){
cpath.add(root.val);
result.add(cpath);
}
List temp = new ArrayList();
temp.addAll(cpath);
temp.add(root.val);
dfs(root.left, sum-root.val, temp, result);
dfs(root.right, sum-root.val, temp, result);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(12);
root.left = new TreeNode(7);
root.right = new TreeNode(1);
root.left.left = new TreeNode(4);
root.right.left = new TreeNode(10);
root.right.right = new TreeNode(5);
int sum = 18;
List> result = FindAllTreePaths.findPaths(root, sum);
System.out.println("Tree paths with sum " + sum + ": " + result);
}
}
另外,我尝试了以下代码,它是上述方案的缩放版本:
public class Main {
public static void main(String[] args) {
int c = call();
System.out.println(c);
}
public static int call(){
int c=100;
call1(c);
return c;
}
private static void call1(int d){
c=4;
d = 4;
}
}
结果是:c = 100
这表明c对于call1()不是全局的。
编辑:我被尝试以下代码,因为我被告知引用类型变量是通过引用传递的,但这不是正确的:
public class Main {
public static void main(String[] args) {
call();
}
public static void call(){
String c="Jack";
List l = new ArrayList();
l.add(1);
call1(c, l);
System.out.println(c);
System.out.println(l.get(0) + " " + l.get(1));
}
private static void call1(String c, List l){
l.add(2);
c="Jack Ryan";
}
}
但是输出是:Jack 1 2
这意味着String通过值传递,而List通过引用传递。