For example:
Given the below binary tree and
sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1return
[ [5,4,11,2], [5,8,4,5] ]
---
Solution: Maintain a current list of node values as you are recursing down each path. Subtract the node's value from sum each time. When you reach a leaf node (node.left == node.right == null), check if the sum is 0. If it were 0, add it to the list of answers.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> answer = new ArrayList<>();
if (root == null) return answer;
pathSum(answer, new ArrayList<Integer>(), root, sum);
return answer;
}
private void pathSum(List<List<Integer>> answer, List<Integer> list, TreeNode node, int sum) {
sum -= node.val;
list.add(node.val);
if (node.left == null && node.right == null) {
if (sum == 0) answer.add(new ArrayList<Integer>(list));
} else {
if (node.left != null) pathSum(answer, list, node.left, sum);
if (node.right != null) pathSum(answer, list, node.right, sum);
}
list.remove(list.size() - 1);
}
}
No comments:
Post a Comment