Sum of Paths II


Problem : Give you the root node root of the binary tree and an integer target and targetSum, and find all the paths whose total path from the root node to the leaf node is equal to the given target sum.

Leaf nodes are nodes that have no child nodes.

Insert picture description here

Analysis:
We can use the depth-first search method to enumerate each path from the root node to the leaf node. When we traverse to the leaf node, and the path sum is just the target sum at this time, we have found a path that satisfies the conditions.

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

class Solution {
    
    
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
    
    
      List<List<Integer>> ans = new ArrayList<>();
      List<Integer> path=new ArrayList<>();
        int path_value=0;
        dfs(root,sum,path_value,path,ans);
        return ans;  
    }
    public void dfs(TreeNode root, int sum,int path_value,List<Integer> path, List<List<Integer>> ans){
    
      
       if(root==null){
    
    
           return;
       } 
        path_value+=root.val;
        path.add(root.val);
        if(root.left==null && root.right==null && path_value==sum){
    
    
            ans.add(new ArrayList<Integer>(path));
        }
        dfs(root.left,sum,path_value,path,ans);
        dfs(root.right,sum,path_value,path,ans);
        path_value-=root.val;
        path.remove(path.size()-1);
        }
    }



Source: LeetCode
Link: https://leetcode-cn.com/problems/path-sum-ii
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/weixin_42120561/article/details/114372985