xinyu04

导航

LeetCode 437 Path Sum III DFS

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).

Solution

和以往的题目不同:只需要找到树中的一条路径即可。因此一个相对暴力的做法就是以每个节点为 \(root\) 进行求解这颗树下的方案数,那么递归来看的话:

\[\text{dfs}(root)+\text{pathSum}(root.left,targetSum)+\text{pathSum}(root.left,targetSum) \]

现在对于每棵树,我们用 \(dfs\) 来递归答案

点击查看代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    long long dfs(TreeNode* root, long long prev, int targetSum){
        if(!root) return 0;
        long long cur = prev + root->val;
        return (cur==targetSum) + dfs(root->right, cur, targetSum) + dfs(root->left, cur, targetSum);
    }
public:
    int pathSum(TreeNode* root, int targetSum) {
        if(!root) return 0;
        return dfs(root, 0, targetSum) + pathSum(root->left, targetSum) + pathSum(root->right, targetSum);
    }
};

posted on 2022-05-19 21:47  Blackzxy  阅读(14)  评论(0编辑  收藏  举报