题目:
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] ]
/**
* 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>> pathSum(TreeNode* root, int sum) {
vector<vector<int> > res;
vector<int> oneCombination;
pathSumCore(root, sum, oneCombination, res);
return res;
}
private:
void pathSumCore(TreeNode* root, int sum, vector<int> oneCombination, vector<vector<int> > &res){
if(NULL == root) return;
oneCombination.push_back(root->val);
if(NULL == root->left && NULL == root->right){//叶节点
if(root->val == sum) res.push_back(oneCombination);
return;
}
int sumNew = sum-root->val;
if(root->left) pathSumCore(root->left, sumNew, oneCombination, res);
if(root->right) pathSumCore(root->right, sumNew, oneCombination, res);
}
};
oneCombination采用引用的话效率更高(24ms vs 12ms)
/**
* 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>> pathSum(TreeNode* root, int sum) {
vector<vector<int> > res;
vector<int> oneCombination;
pathSumCore(root, sum, oneCombination, res);
return res;
}
private:
void pathSumCore(TreeNode* root, int sum, vector<int> &oneCombination, vector<vector<int> > &res){
if(NULL == root) return;
oneCombination.push_back(root->val);
if(NULL == root->left && NULL == root->right){//叶节点
if(root->val == sum) res.push_back(oneCombination);
return;
}
int sumNew = sum-root->val;
if(root->left){
pathSumCore(root->left, sumNew, oneCombination, res);
oneCombination.pop_back();
}
if(root->right){
pathSumCore(root->right, sumNew, oneCombination, res);
oneCombination.pop_back();
}
}
};