0
点赞
收藏
分享

微信扫一扫

力扣437. 路径总和 III

您好 2024-05-08 阅读 36

文章目录

题目描述

思路

复杂度

时间复杂度:

空间复杂度:

Code

/**
 * 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;
 *     }
 * }
 */
class Solution {
    /**
     * Path Sum III
     *
     * @param root      The root of binary tree
     * @param targetSum The target number
     * @return int
     */
    public int pathSum(TreeNode root, long targetSum) {
        if (root == null) {
            return 0;
        }
        int res = rootSum(root, targetSum);
        res += pathSum(root.left, targetSum);
        res += pathSum(root.right, targetSum);
        return res;
    }

    /**
     * Find the sum of the target paths of each node
     *
     * @param root      The root of binary tree
     * @param targetSum The target number
     * @return int
     */
    public int rootSum(TreeNode root, long targetSum) {
        int res = 0;
        if (root == null) {
            return 0;
        }
        int value = root.val;
        if (value == targetSum) {
            res++;
        }
        res += rootSum(root.left, targetSum - value);
        res += rootSum(root.right, targetSum - value);
        return res;
    }
}
举报

相关推荐

0 条评论