All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0401_0500.s0437_path_sum_iii.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0401_0500.s0437_path_sum_iii;

// #Medium #Top_100_Liked_Questions #Depth_First_Search #Tree #Binary_Tree #Level_2_Day_7_Tree
// #Big_O_Time_O(n)_Space_O(n) #2022_07_16_Time_18_ms_(45.66%)_Space_42_MB_(88.96%)

import com_github_leetcode.TreeNode;

/*
 * 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;
 *     }
 * }
 */
/**
 * 437 - Path Sum III\.
 *
 * Medium
 *
 * Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`.
 *
 * The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
 *
 * **Example 1:**
 *
 * ![](https://assets.leetcode.com/uploads/2021/04/09/pathsum3-1-tree.jpg)
 *
 * **Input:** root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
 *
 * **Output:** 3
 *
 * **Explanation:** The paths that sum to 8 are shown. 
 *
 * **Example 2:**
 *
 * **Input:** root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
 *
 * **Output:** 3 
 *
 * **Constraints:**
 *
 * *   The number of nodes in the tree is in the range `[0, 1000]`.
 * *   -109 <= Node.val <= 109
 * *   `-1000 <= targetSum <= 1000`
**/
public class Solution {
    private int count = 0;

    public int pathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return 0;
        }
        helper(root, targetSum, 0);
        pathSum(root.left, targetSum);
        pathSum(root.right, targetSum);
        return count;
    }

    public void helper(TreeNode node, int targetSum, long currSum) {
        currSum += node.val;
        if (targetSum == currSum) {
            count++;
        }
        if (node.left != null) {
            helper(node.left, targetSum, currSum);
        }
        if (node.right != null) {
            helper(node.right, targetSum, currSum);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy