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

/*** 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 {List<List<Integer>> res = new ArrayList<>();List<Integer> list = new ArrayList<>();public List<List<Integer>> pathSum(TreeNode root, int targetSum) {helper(root, targetSum);return res;}public void helper (TreeNode root, int sum) {if (root == null) return;sum = sum - root.val;list.add(root.val);if (root.left == null && root.right == null && sum == 0) {res.add(new ArrayList<>(list));}helper(root.left, sum);helper(root.right,sum);list.remove(list.size() - 1);}}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-ii
