题目描述:
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example: Given the below binary tree andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 27 1
return
[
[5,4,11,2],
[5,8,4,5]
]
解题思路:
- 这道题与上一题解题思路一致,需要注意的地方是因为要利用函数自身来递归,所以设置全局变量
代码如下:
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
ArrayList<Integer> templist = new ArrayList<>();
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
if(root == null) return res;
sum -= root.val;
templist.add(root.val);
if(sum == 0 && root.left == null && root.right == null){
res.add(new ArrayList<>(templist));
}
else{
pathSum(root.left,sum);
pathSum(root.right, sum);
}
templist.remove(templist.size() - 1);
return res;
}