一、题目内容

image.png
image.png

二、题解

解法1:

思路

定义ans、path(LinkedList)
先序遍历,每次将根的值加入path,判断是否为叶子节点并且target减为0,true则加入ans
否则继续先序遍历左右,遍历完成后移除当前节点回溯

代码

  1. public class Solution {
  2. private ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
  3. private LinkedList<Integer> path = new LinkedList<>();
  4. public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {
  5. // write code here
  6. recur(root, sum);
  7. return ans;
  8. }
  9. public void recur(TreeNode root, int target){
  10. if (root == null) {
  11. return;
  12. }
  13. path.add(root.val);
  14. target -= root.val;
  15. if (target == 0 && root.left == null && root.right == null) {
  16. ans.add(new ArrayList<>(path));
  17. }
  18. recur(root.left, target);
  19. recur(root.right, target);
  20. path.removeLast();
  21. }
  22. }