题目
给定一个二叉树的根节点 root
,和一个整数 targetSum
,求该二叉树里节点值之和等于 targetSum
的 路径 的数目。
路径 不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
示例 1:
输入:root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 输出:3 解释:和等于 8 的路径有 3 条,如图所示。
示例 2:
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 输出:3
提示:
- 二叉树的节点个数的范围是
[0,1000]
-109 <= Node.val <= 109
-1000 <= targetSum <= 1000
思路
统计以每个节点为根,向下遍历有多少个路径总和为targetSum的。
于是我们用dfs1来遍历每个节点,在dfs1中对于每个节点,用dfs2来搜索以其为根的所有向下的路径,同时累加路径总和 为targetSum的所有路径。
class Solution {
int ans, t;
public int pathSum(TreeNode root, int targerSum) {
t = targetSum;
dfs1(root);
return ans;
}
void dfs1(TreeNode root) {
if (root == null) return;
dfs2(root, root.val);
dfs1(root.left);
dfs1(root.right);
}
void dfs2(TreeNode root, long val) {
if (val == t) ans++;
if (root.left != null) dfs2(root.left, val + root.left.val);
if (root.right != null) dfs2(root.right, val + root.right.val);
}
}