LeetCode113:
    给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
    叶子节点 是指没有子节点的节点。

    1. class Solution {
    2. List<List<Integer>> linkedList = new LinkedList<>();
    3. public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
    4. if(root == null){
    5. return new LinkedList<>();
    6. }
    7. LinkedList<Integer> list = new LinkedList<>();
    8. list.addLast(root.val);
    9. dfs(root, root.val, targetSum, list);
    10. return linkedList;
    11. }
    12. private void dfs(TreeNode node, int val, int targetSum, LinkedList<Integer> list) {
    13. if (node == null) {
    14. return;
    15. }
    16. if (node.right == null && node.left == null) {
    17. if (val == targetSum) {
    18. //新创建列表的原因,否则始终添加是同一个列表
    19. linkedList.add(new LinkedList<>(list));
    20. }
    21. return;
    22. }
    23. if (node.left != null){
    24. //回溯要注意有增,也要有删
    25. //否则会在原来的基础上不断增加,应该后面的回溯
    26. list.addLast(node.left.val);
    27. dfs(node.left, val + node.left.val, targetSum, list);
    28. list.pollLast();
    29. }
    30. if (node.right != null){
    31. list.addLast(node.right.val);
    32. dfs(node.right, val + node.right.val, targetSum, list);
    33. list.pollLast();
    34. }
    35. }
    36. }