題目描述
題目難度:Medium
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Note: A leaf is a node with no children.
AC代碼
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> resList = new ArrayList<>();
if(root == null) return resList;
helper(root, sum, 0, resList, new ArrayList<Integer>());
return resList;
}
private void helper(TreeNode root, int sum, int cur, List<List<Integer>> resList, List<Integer> list){
if(root == null) return;
if(root.left == null && root.right == null){
if(cur + root.val == sum){
list.add(root.val);
resList.add(new ArrayList(list));
list.remove(list.size() - 1);
return;
}
}
list.add(root.val);
helper(root.left, sum, cur + root.val, resList, list);
helper(root.right, sum, cur + root.val, resList, list);
list.remove(list.size() - 1);
}
}