对每个节点进行深搜,当然了没到叶子节点就得到结果的话还要继续往下搜因为还有可能组成另一条路径。
/** * 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 { public: int pathSum(TreeNode* root, int targetSum) { if(!root) return 0; int lastres=DFS(root,targetSum); lastres+=pathSum(root->left,targetSum); lastres+=pathSum(root->right,targetSum); return lastres; } int DFS(TreeNode* root,int targetSum) { if(root==nullptr) { return 0; } int res=0; if(root->val==targetSum) { res+=1; } res+=DFS(root->left,targetSum-root->val); res+=DFS(root->right,targetSum-root->val); return res; } };