|
| 1 | +package com.diguage.algo.leetcode; |
| 2 | + |
| 3 | +import com.diguage.algo.util.TreeNode; |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.LinkedList; |
| 7 | +import java.util.List; |
| 8 | + |
| 9 | +import static com.diguage.util.TreeNodes.buildTree; |
| 10 | +import static java.util.Arrays.asList; |
| 11 | + |
| 12 | +public class _0113_PathSumII_3 { |
| 13 | + // tag::answer[] |
| 14 | + |
| 15 | + /** |
| 16 | + * @author D瓜哥 · https://www.diguage.com |
| 17 | + * @since 2024-06-20 18:48 |
| 18 | + */ |
| 19 | + public List<List<Integer>> pathSum(TreeNode root, int targetSum) { |
| 20 | + List<List<Integer>> result = new LinkedList<>(); |
| 21 | + List<Integer> path = new ArrayList<>(); |
| 22 | + backtrack(root, targetSum, result, path); |
| 23 | + return result; |
| 24 | + } |
| 25 | + |
| 26 | + private void backtrack(TreeNode root, int targetSum, |
| 27 | + List<List<Integer>> result, List<Integer> path) { |
| 28 | + if (root == null) { |
| 29 | + return; |
| 30 | + } |
| 31 | + int nextSum = targetSum - root.val; |
| 32 | + path.add(root.val); |
| 33 | + if (nextSum == 0 && root.left == null && root.right == null) { |
| 34 | + result.add(new ArrayList(path)); |
| 35 | + } |
| 36 | + backtrack(root.left, nextSum, result, path); |
| 37 | + backtrack(root.right, nextSum, result, path); |
| 38 | + path.remove(path.size() - 1); |
| 39 | + } |
| 40 | + // end::answer[] |
| 41 | + |
| 42 | + public static void main(String[] args) { |
| 43 | + _0113_PathSumII_3 solution = new _0113_PathSumII_3(); |
| 44 | + List<List<Integer>> r1 = solution.pathSum(buildTree(asList(5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, null, 5, 1)), 22); |
| 45 | + System.out.println(r1); |
| 46 | + } |
| 47 | +} |
0 commit comments