方法1:DFS
List<List<Integer>> res = new ArrayList<>();
int target;
public List<List<Integer>> binaryTreePathSum2(TreeNode root, int target) {
this.target = target;
dfs(root, new ArrayList<>());
return res;
}
private void dfs(TreeNode root, List<Integer> sub) {
if (root == null) return;
sub.add(root.val);
int sum = 0;
for (int i = sub.size() - 1; i >= 0; --i) {
sum += sub.get(i);
if (sum == target) res.add(new ArrayList<>(sub.subList(i, sub.size())));
}
dfs(root.left, sub);
dfs(root.right, sub);
sub.remove(sub.size() - 1);
}
方法2:DFS
List<List<Integer>> res = new ArrayList<>();
int target;
public List<List<Integer>> binaryTreePathSum2(TreeNode root, int target) {
this.target = target;
dfs(root, 0, new ArrayList<>(), false);
return res;
}
private void dfs(TreeNode root, int sum, List<Integer> path, boolean needRestart) {
if (root == null) return;
sum += root.val;
path.add(root.val);
if (sum == target) res.add(new ArrayList<>(path));
dfs(root.left, sum, path, true);
dfs(root.right, sum, path, true);
if (!needRestart) {
dfs(root.left,0,new ArrayList<>(),false);
dfs(root.right,0,new ArrayList<>(),false);
}
path.remove(path.size()-1);
}