路径总和 II (Path Sum II)

 

思路:回溯

// @Title: 路径总和 II (Path Sum II)
// @Author: qisiii
// @Date: 2024-10-13 23:18:30
// @Runtime: 1 ms
// @Memory: 43.6 MB
// @comment: 回溯
// @flag: WHITE
/**
 * 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 targetSum) {
        List<List<Integer>> result=new ArrayList<>();
        dfs(result,new ArrayList<>(),root,targetSum);
        return result;
    }
    private void dfs(List<List<Integer>> result,List<Integer> path,TreeNode node,int targetSum){
        if(node==null){
            return;
        }
        path.add(node.val);
        if(node.left==null&&node.right==null){
            if(targetSum==node.val){
                result.add(new ArrayList<>(path));
            }
            path.remove(path.size()-1);
            return;
        }
        dfs(result,path,node.left,targetSum-node.val);
        dfs(result,path,node.right,targetSum-node.val);
        path.remove(path.size()-1);
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18