题目大意:
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
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]意思就是:
紧跟Path Sum,只是需要输出各种可能的情况.
/**
* 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) {
result.clear();
if(!root){
return result;
}
vector<int> a;
dfsTravel(root, sum, a);
return result;
}
void dfsTravel(TreeNode* node, int rest, vector<int> a){
rest = rest - node->val;
a.push_back(node->val);
if(rest == 0 && !node->left && !node->right){
result.push_back(a);
return;
}
if(node->left){
dfsTravel(node->left, rest, a);
}
if(node->right){
dfsTravel(node->right, rest, a);
}
}
private:
vector< vector<int> > result;
};