题意:找出各结点之和为给定值的所有路径。
思路:DFS。
/**
* 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> > re;
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if(root == NULL) return re;
vector<int> temp;
dfs(temp, root, sum);
return re;
}
int dfs(vector<int> tempre, TreeNode* root, int sum) {
if(root == NULL) return 0;
tempre.push_back(root->val);
if(sum - root->val == 0 && root->left == NULL && root->right == NULL) {
re.push_back(tempre);
return 0;
}
dfs(tempre, root->left, sum - root->val);
dfs(tempre, root->right, sum - root->val);
return 0;
}
};