public class Solution {标签:结点,helper,int,res,sum,路径,二叉树,root,一值 From: https://www.cnblogs.com/MarkLeeBYR/p/17166229.html
private int res = 0;
//dfs 以每个结点作为根查询路径
public int findPath (TreeNode root, int sum) {
//为空则返回
if(root == null)
return res;
//查询以某结点为根的路径数
helper(root, sum);
//以其子结点为新根
findPath(root.left, sum);
findPath(root.right, sum);
return res;
}
//dfs查询以某结点为根的路径数
private void helper(TreeNode root, int sum){
if(root == null)
return;
//符合目标值
if(sum == root.val)
res++;
//进入子节点继续找
helper(root.left, sum - root.val);
helper(root.right, sum - root.val);
}
}