1. 程式人生 > 其它 >LeetCode 437 Path Sum III DFS

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);
    }
};