这里要注意空间复杂度,回溯的时候要从路径集合中去掉最后加入的点。值得细品。
    image.png
    我的代码效率不是很高
    https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/solution/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-68dg/
    主要在temp列表进行赋值的时候,好的方法是用回溯,我这个是每一次都开辟两个空间,

    1. public static void main(String[] args) {
    2. TreeNode node1 = new TreeNode(1);
    3. TreeNode node2 = new TreeNode(2);
    4. TreeNode node3 = new TreeNode(3);
    5. node1.left = node2;
    6. //node1.right = node3;
    7. List<List<Integer>> res ;
    8. res = pathSum(node1,4);
    9. System.out.println(res.size());
    10. }
    11. public static List<List<Integer>> pathSum(TreeNode root, int target) {
    12. if(root == null ) new ArrayList<>();
    13. List<List<Integer>> res = new ArrayList<>();
    14. process(root, target, 0, new ArrayList<>(), res);
    15. return res;
    16. }
    17. public static void process(TreeNode root, int target, int cur, List<Integer> list, List<List<Integer>> lists ){
    18. if(root == null )return;
    19. if(root.left == null && root.right==null ) {
    20. if(cur + root.val == target){
    21. list.add(root.val);
    22. lists.add(list);
    23. }
    24. return ;
    25. }
    26. List<Integer> temp = new ArrayList<>();
    27. temp.addAll(list);
    28. temp.add(root.val);
    29. process(root.left, target, cur + root.val, temp , lists);
    30. List<Integer> temp2 = new ArrayList<>();
    31. temp2.addAll(list);
    32. temp2.add(root.val);
    33. process(root.right, target, cur + root.val, temp2 , lists);
    34. }
    35. public static class TreeNode {
    36. int val;
    37. TreeNode left;
    38. TreeNode right;
    39. TreeNode() {}
    40. TreeNode(int val) { this.val = val; }
    41. TreeNode(int val, TreeNode left, TreeNode right) {
    42. this.val = val;
    43. this.left = left;
    44. this.right = right;
    45. }
    46. }

    看官方题解:
    image.png
    解法2: 广度优先,也要额外维护一个和队列,跟路径一一对应。
    通过深入理解回溯思想,改进代码

    1. public static void process(TreeNode root, int target, int cur, List<Integer> list, List<List<Integer>> lists ){
    2. if(root == null )return;
    3. if(root.left == null && root.right==null ) {
    4. if(cur + root.val == target){
    5. List<Integer> temp = new ArrayList<>();
    6. temp.addAll(list);
    7. temp.add(root.val);
    8. lists.add(temp);
    9. }
    10. return ;
    11. }
    12. list.add(root.val);
    13. process(root.left, target, cur + root.val, list , lists);
    14. process(root.right, target, cur + root.val, list , lists);
    15. list.remove(list.size()-1);
    16. }

    时间从超过2.5%的用户提高到超过100%的用户。
    image.png