解析: 返回二叉树中路径和为sum的路径的个数,它无需从root开始以leaf结束
solutions:
1.以每一个结点为路径的根结点进行前序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
if(!root) return 0;
return findpath(root,0,sum)+pathSum(root->left,sum)+pathSum(root->right,sum);
}
int findpath(TreeNode* root,int curSum,int sum)
{
if(!root) return 0;
curSum = curSum + root->val;
return (curSum == sum) + findpath(root->left,curSum,sum) + findpath(root->right,curSum,sum);
}
};
2.DFS,这是典型的DFS问题
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
// if(!root) return 0;
vector<TreeNode*> vec;
int res = 0;
findpath(root,sum,0,res,vec);
return res;
}
void findpath(TreeNode* node,int sum,int curSum,int &res,vector<TreeNode*> &vec)
{
if(!node) return;//退出条件
curSum = curSum + node->val;//从根结点到当前结点的路径的所有权值的和
vec.push_back(node);
if(sum == curSum) res++;
int tmp = curSum;
//判断子路径的和
for(int i = 0;i<vec.size()-1;i++)
{
tmp = tmp-vec[i]->val;
if(tmp == sum) res++;
}
findpath(node->left,sum,curSum,res,vec);
findpath(node->right,sum,curSum,res,vec);
vec.pop_back();//回溯条件
}
};