二叉树的路径问题dfs:
    力扣257,404,112路径总和,437路径总和

    1. 1.二叉树的所有路径(带回溯)
    2. public List<String> binaryTreePaths(TreeNode root) {
    3. if(root==null){
    4. return res;
    5. }
    6. backTrack(root);
    7. return res;
    8. }
    9. private void backTrack(TreeNode root){
    10. path.add(root.val);
    11. if(root.left==null&&root.right==null){
    12. for(int i=0;i<path.size();i++){
    13. sb.append(path.get(i)).append("->");
    14. }
    15. res.add(sb.toString().substring(0,sb.length()-2));
    16. sb=new StringBuilder();
    17. return;
    18. }
    19. if(root.left!=null){
    20. backTrack(root.left);
    21. path.remove(path.size()-1);
    22. }
    23. if(root.right!=null){
    24. backTrack(root.right);
    25. path.remove(path.size()-1);
    26. }
    1. 2.左叶子之和
    2. if(root==null){
    3. return res;
    4. }
    5. findSum(root);
    6. return res;
    7. }
    8. private int findSum(TreeNode root){
    9. if(root==null){
    10. return 0;
    11. }
    12. int leftSum = findSum(root.left);
    13. int rightSum = findSum(root.right);
    14. if(root.left!=null&&root.left.left==null&&root.left.right==null){
    15. res+=root.left.val;
    16. }
    17. return res;
    1. 3.路径总和
    2. if(root==null){
    3. return res;
    4. }
    5. backTrack(root,targetSum);
    6. return res;
    7. }
    8. private void backTrack(TreeNode root,int targetSum){
    9. sum+=root.val;
    10. if(root.left==null&&root.right==null){
    11. if(sum==targetSum){
    12. res=true;
    13. return;
    14. }else{
    15. return;
    16. }
    17. }
    18. if(root.left!=null) {
    19. backTrack(root.left, targetSum);
    20. sum-=root.left.val;
    21. }
    22. if(root.right!=null) {
    23. backTrack(root.right, targetSum);
    24. sum-=root.right.val;
    25. }
    26. }
    1. 4.路径总和(前缀和)
    2. if(root==null){
    3. return res;
    4. }
    5. Map<Integer,Integer>map=new HashMap<>();
    6. map.put(0,1);
    7. findPathSum(root,targetSum,map,0);
    8. return res;
    9. }
    10. private void findPathSum(TreeNode root,int targetSum,Map<Integer,Integer>map,int sum){
    11. if(root==null){
    12. return;
    13. }
    14. sum+=root.val;
    15. if(map.containsKey(sum-targetSum)){
    16. res+=map.get(sum-targetSum);
    17. }
    18. map.put(sum,map.getOrDefault(sum,0)+1);
    19. findPathSum(root.left,targetSum,map,sum);
    20. findPathSum(root.right,targetSum,map,sum);
    21. map.put(sum,map.getOrDefault(sum,0)-1);