方法一:双重递归
遇到问题:数据溢出,将int类型改为long类型
/*** 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 result=0;int pathSum(TreeNode* root, long targetSum) {if(root==NULL){return 0;}hasPathSum(root,targetSum);pathSum(root->left,targetSum);pathSum(root->right,targetSum);return result;}void hasPathSum(TreeNode* root, long targetSum) {if(root==NULL){return;}if(targetSum==root->val){result=result+1;}hasPathSum(root->left,targetSum-root->val);hasPathSum(root->right,targetSum-root->val);}};
方法二:将节点root前面所以的父节点的val累加起来(rootsum),以该累加的值减去目标路径长度,若在哈希表中可以查找到该值出现的次数(count)即为有count条路径,并将rootsum存入哈希表之中,同时在后序遍历时,因为路径是由上往下的方向,在子节点进行返回时,为了不让后面的子节点印象前面的父节点,我们对哈希表中rootsum的出现次数进行一个减减的操作
class Solution {public:unordered_map<long,int>presum;int result=0;int pathSum(TreeNode* root, int targetSum) {if(!root){return 0;}presum[0]=1;dfs(root,targetSum,0);return result;}void dfs(TreeNode* root, int targetSum, long rootsum){if(root==NULL){return;}rootsum+=root->val;if(presum.count(rootsum-targetSum)){result+=presum[rootsum-targetSum];}presum[rootsum]+=1;dfs(root->left,targetSum,rootsum);dfs(root->right,targetSum,rootsum);presum[rootsum]--;}};
