二叉树中和为某一值的路径
path数组时刻记录着当前所行走的路径
只有当遍历到叶子结点的时候进行 求和的判断 看是否能把路径添加到结果数组res中.
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int expect;
vector<vector<int> >res;
vector<int> path;
void recur(TreeNode* node)
{
if(node == NULL)return ;
if(node->left == NULL && node->right == NULL)
{
path.push_back(node->val);
int sum = 0;
for(int i=0;i<path.size();i++)
{
sum += path[i];
}
if(sum == expect)
{
res.push_back(path);
}
path.pop_back();
return ;
}
path.push_back(node->val);
recur(node->left);
recur(node->right);
path.pop_back();
}
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
expect = expectNumber;
if(root == NULL)return res;
recur(root);
return res;
}
};