没什么要说的。注意父节点在左右子树返回时可能被计算两次。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int>> res;
vector<int> path;
if (root == NULL)
return res;
dfs(root, sum, 0, res, path);
return res;
}
void dfs(TreeNode *root, int sum, int total, vector<vector<int>> &res, vector<int> &path) {
if (root == NULL)
return;
path.push_back(root->val);
if (root->left == NULL && root->right == NULL && total + root->val == sum)
res.push_back(path);
dfs(root->left, sum, total + root->val, res, path);
dfs(root->right, sum, total + root->val, res, path);
path.pop_back();
}
};
http://oj.leetcode.com/problems/path-sum-ii/