2021年9月12日09:04:01
2021年9月12日09:27:52
可以把 sum 优化掉、
res.add(new ArrayList<integer>(temp));
注意添加的时候不能 res.add(temp)</integer>
他添加的结果会根据temp变化(只加入了temp的头结点) 所以需要新建一个 列表 初始化
temp.remove(temp.size() - 1); remove最后一个
2.
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
ArrayList<Integer> temp = new ArrayList<Integer>();
curpath(root,target,temp);
return res;
}
public void curpath(TreeNode root,int target, ArrayList<Integer> temp){
if(root == null) return ;
temp.add(root.val);
target = target - root.val;
if(root.left == null && root.right == null && 0 == target){
res.add(new ArrayList<Integer>(temp));
}
curpath(root.left, target, temp);
curpath(root.right, target, temp);
temp.remove(temp.size() - 1);
return ;
}
}1.
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
ArrayList<Integer> temp = new ArrayList<Integer>();
curpath(root,0,target,temp);
return res;
}
public void curpath(TreeNode root, int sum, int target, ArrayList<Integer> temp){
if(root == null) return ;
temp.add(root.val);
sum = sum + root.val;
if(root.left == null && root.right == null && sum == target){
res.add(new ArrayList<Integer>(temp));
}
curpath(root.left, sum, target, temp);
curpath(root.right, sum, target, temp);
temp.remove(temp.size() - 1);
return ;
}
}


京公网安备 11010502036488号