Skip to main content

Command Palette

Search for a command to run...

path sum -3

Updated
1 min readView as Markdown
/**
 * 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);
    }
}

More from this blog

Amit singh's blog

235 posts