path sum -3
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int val) { this.val = val; }
* }
*/
public class Solution {
static int totalPaths = 0;
public static int pathSum(TreeNode root, int targetSum) {
totalPaths = 0;
dfs(root, targetSum);
return totalPaths;
}
private static void dfs(TreeNode node, int targetSum) {
if (node == null) return;
// count paths from current node
countPathsFromNode(node, targetSum);
// recurse on left and right
dfs(node.left, targetSum);
dfs(node.right, targetSum);
}
private static void countPathsFromNode(TreeNode node, long targetSum) {
if (node == null) return;
if (node.val == targetSum) {
totalPaths++;
}
countPathsFromNode(node.left, targetSum - node.val);
countPathsFromNode(node.right, targetSum - node.val);
}
}