解析:
这题是个二叉树问题,需要从上到下遍历每个节点,所以可以采用前序遍历,先可以写个框架出来
public void help(TreeNode root,int target) {
path.add(root.val);
if(root.left != null) {
help(root.left, target);
}
if(root.right != null) {
help(root.right, target);
}
path.remove(path.size() - 1);
}
这个就是前序遍历的框架,然后在想,我要把满足条件的节点放进集合,什么时候才可以把该路径的节点放进集合,满足一下条件即可
if(root.left == null && root.right == null && root.val == target) {
res.add(new ArrayList<>(path));
}
然后向左右递归,递归完后,会返回上一个节点,这个时候需要把该节点从集合删除,尝试其他的情况
import java.util.ArrayList;
public class Solution {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
ArrayList<Integer> path = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root == null) {
return res;
}
help(root, target);
return res;
}
public void help(TreeNode root,int target) {
path.add(root.val);
if(root.left == null && root.right == null && root.val == target) {
res.add(new ArrayList<>(path));
}
if(root.left != null) {
help(root.left, target - root.val);
}
if(root.right != null) {
help(root.right, target - root.val);
}
path.remove(path.size() - 1);
}
}