Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
Return
思路:
用全局变量来记录res和temp, temp就是过程中的从上到下的路径。
/**
* 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:
vector<vector<int> > res;
vector<int> temp;
void path(TreeNode* root, int tempsum, int sum){
if(root==NULL) return;
tempsum=tempsum+root->val;
temp.push_back(root->val);
if(root->left==NULL && root->right==NULL && tempsum==sum)
{
res.push_back(temp);
}
path(root->left,tempsum,sum);
path(root->right,tempsum,sum);
temp.pop_back();
}
vector<vector<int> > pathSum(TreeNode* root, int sum) {
if(root==NULL) return res;
path(root,0,sum);
return res;
}
};