public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> results = new ArrayList<>();
if (root != null) {
List<Integer> path = new ArrayList<>();
path.add(root.val);
this.helper(root, sum - root.val, path, results);
}
return results;
}
private void helper(TreeNode root, int sum, List<Integer> path, List<List<Integer>> results) {
if (sum == 0) {
if (root.left == null && root.right == null) { // 题目要求必须是leaf
List<Integer> temp = new ArrayList<Integer>(path);
results.add(temp);
}
return;
}
if (root.left != null) {
path.add(root.left.val);
this.helper(root.left, sum - root.left.val, path, results);
path.remove(path.size() - 1);
}
if (root.right != null) {
path.add(root.right.val);
this.helper(root.right, sum - root.right.val, path, results);
path.remove(path.size() - 1);
}
}
}
近期评论