leetcode-437-路径总和III

leetcode-437-路径总和III_第1张图片

class Solution {

public:

    //包含root结点的条数

    int findPath(TreeNode* root, int sum){

        int res = 0;

        if (root){

            if (root->val == sum) res++;

           // if (root->left == NULL && root->right == NULL) return res;

            res += findPath(root->left, sum-root->val);

            res += findPath(root->right, sum-root->val);

        }

        return res;

    }

 

    int pathSum(TreeNode* root, int sum) {

        int res =0;

        if (root){

            res = findPath(root, sum) ;

            res += pathSum(root->left, sum);

            res += pathSum(root->right, sum);

        }

        return res;

    }

};

你可能感兴趣的:(递归,树,leetcode备份-简单)