/**
* @author xnl
* @Description:
* @date: 2022/6/27 22:47
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
}
public int pathSum(TreeNode root, int sum) {
if (root == null){
return 0;
}
// 遍历以每一个节点为根节点的数,找到结果,相加返回
int res = bfs(root, sum);
res += pathSum(root.left, sum);
res += pathSum(root.right, sum);
return res;
}
private int bfs(TreeNode root, int sum){
if (root == null){
return 0;
}
// 结果
int res = 0;
int value = root.val;
// 如果说得到了结果就把结果加一
if (sum == value){
res++;
}
// 一直递归,直到找到结果
res += bfs(root.left, sum - value);
res += bfs(root.right, sum - value);
return res;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
力扣:面试题 04.12. 求和路径
最新推荐文章于 2024-11-07 23:56:45 发布