|
4 | 4 | * int val; |
5 | 5 | * TreeNode left; |
6 | 6 | * TreeNode right; |
7 | | - * TreeNode(int x) { val = x; } |
| 7 | + * TreeNode() {} |
| 8 | + * TreeNode(int val) { this.val = val; } |
| 9 | + * TreeNode(int val, TreeNode left, TreeNode right) { |
| 10 | + * this.val = val; |
| 11 | + * this.left = left; |
| 12 | + * this.right = right; |
| 13 | + * } |
8 | 14 | * } |
9 | 15 | */ |
10 | 16 | class Solution { |
| 17 | + public List<List<Integer>> pathSum(TreeNode root, int targetSum) { |
11 | 18 | List<List<Integer>> list = new ArrayList<>(); |
12 | | - public List<List<Integer>> pathSum(TreeNode root, int sum) { |
13 | | - if (root == null) return list; |
14 | | - |
15 | | - Stack<Integer> path = new Stack<>(); |
16 | | - |
17 | | - pathSumImpl(root, sum, path); |
18 | | - return list; |
| 19 | + helper(root, targetSum, new ArrayList<>(), list); |
| 20 | + return list; |
| 21 | + } |
| 22 | + |
| 23 | + private void helper(TreeNode root, int targetSum, List<Integer> curr, List<List<Integer>> list) { |
| 24 | + if (root == null) { |
| 25 | + return; |
19 | 26 | } |
20 | | - |
21 | | - private void pathSumImpl(TreeNode root, int sum, Stack<Integer> path) { |
22 | | - path.push(root.val); |
23 | | - if (root.left == null && root.right == null) { |
24 | | - if (sum == root.val) { |
25 | | - list.add(new ArrayList<Integer>(path)); |
26 | | - } |
27 | | - } |
28 | | - |
29 | | - if (root.left != null) { |
30 | | - pathSumImpl(root.left, sum-root.val, path); |
31 | | - } |
32 | | - |
33 | | - if (root.right != null) { |
34 | | - pathSumImpl(root.right, sum-root.val, path); |
35 | | - } |
36 | | - |
37 | | - path.pop(); |
| 27 | + curr.add(root.val); |
| 28 | + if (isLeaf(root) && (targetSum - root.val) == 0) { |
| 29 | + list.add(new ArrayList<>(curr)); |
38 | 30 | } |
| 31 | + helper(root.left, targetSum - root.val, curr, list); |
| 32 | + helper(root.right, targetSum - root.val, curr, list); |
| 33 | + curr.remove(curr.size() - 1); |
| 34 | + } |
| 35 | + |
| 36 | + private boolean isLeaf(TreeNode root) { |
| 37 | + return root.left == null && root.right == null; |
| 38 | + } |
39 | 39 | } |
0 commit comments