能用Java写吗
时间: 2023-07-01 11:11:54 浏览: 125
当然可以,以下是Java版本的实现:
```java
class Solution {
public int pathSum(TreeNode root, int targetSum) {
List<Integer> sumList = new ArrayList<>();
sumList.add(0);
return dfs(root, sumList, targetSum);
}
public int dfs(TreeNode node, List<Integer> sumList, int targetSum) {
if (node == null) {
return 0;
}
int count = 0;
int curSum = sumList.get(sumList.size() - 1) + node.val;
for (int i = 0; i < sumList.size(); i++) {
if (curSum - sumList.get(i) == targetSum) {
count++;
}
}
sumList.add(curSum);
count += dfs(node.left, sumList, targetSum);
count += dfs(node.right, sumList, targetSum);
sumList.remove(sumList.size() - 1);
return count;
}
}
```
希望对你有帮助!
阅读全文