思路:一个简单的bfs,将每一个节点都作为跟节点遍历一遍就行了
/**
* 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 an = 0;
int tar;
int pathSum(TreeNode* root, int targetSum) {
if(root == nullptr)
return 0;
tar = targetSum;
bianliTree(root);
return an;
}
void bianliTree(TreeNode *nowNode){
dfs(0, nowNode);
if(nowNode->left != nullptr){
bianliTree(nowNode->left);
}
if(nowNode->right != nullptr){
bianliTree(nowNode->right);
}
}
void dfs(long long nowValue, TreeNode *nowNode){
nowValue += nowNode->val;
if(nowValue == tar){
// cout << nowNode->val<< " " << nowValue<< " " << nowNode->val << endl;
an++;
}
if(nowNode->left != nullptr){
dfs(nowValue, nowNode->left);
}
if(nowNode->right != nullptr){
dfs(nowValue, nowNode->right);
}
}
};