|
| 1 | +// https://leetcode.com/problems/path-sum-ii |
| 2 | +// T: O(n * log(n)) |
| 3 | +// S: O(n * log(n)) |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.LinkedList; |
| 7 | +import java.util.List; |
| 8 | + |
| 9 | +public class PathSumII { |
| 10 | + public List<List<Integer>> pathSum(TreeNode root, int targetSum) { |
| 11 | + final List<List<Integer>> result = new ArrayList<>(); |
| 12 | + if (root == null) return result; |
| 13 | + pathSum(root, targetSum, result); |
| 14 | + return result; |
| 15 | + } |
| 16 | + |
| 17 | + private void pathSum(TreeNode root, int targetSum, final List<List<Integer>> result) { |
| 18 | + pathSum(root, targetSum, result, 0, new LinkedList<>()); |
| 19 | + } |
| 20 | + |
| 21 | + private void pathSum(TreeNode root, int targetSum, final List<List<Integer>> result, int sum, LinkedList<Integer> path) { |
| 22 | + path.addLast(root.val); |
| 23 | + sum += root.val; |
| 24 | + |
| 25 | + if (isLeafNode(root)) { |
| 26 | + if (sum == targetSum) result.add(new ArrayList<>(path)); |
| 27 | + return; |
| 28 | + } |
| 29 | + |
| 30 | + if (root.left != null) { |
| 31 | + pathSum(root.left, targetSum, result, sum, path); |
| 32 | + path.removeLast(); |
| 33 | + } |
| 34 | + if (root.right != null) { |
| 35 | + pathSum(root.right, targetSum, result, sum, path); |
| 36 | + path.removeLast(); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + private boolean isLeafNode(TreeNode root) { |
| 41 | + return root.left == null && root.right == null; |
| 42 | + } |
| 43 | +} |
0 commit comments