一. 挺像回溯法, 给定tmp,满足条件添加进入res,否则通过回溯进行查找.
#include <iostream>
#include <vector>
using namespace std;
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> tmp;
vector<vector<int>> pathSum(TreeNode* root, int sum) {
//如果空树,直接返回res.
if (root == NULL) return res;
//如果是叶子节点,并且节点值等于sum,满足情况.
if (root->val == sum&&root->left == NULL&&root->right == NULL){
//加入sum.
tmp.push_back(sum);
res.push_back(tmp);
//别忘了回溯.
tmp.pop_back();
//找到即可返回res.
return res;
}
tmp.push_back(root->val);
//递归左右子树.
res = pathSum(root->left, sum - root->val);
res = pathSum(root->right, sum - root->val);
//返回之前别忘了回溯.
tmp.pop_back();
return res;
}
};
复杂度比较高但是比较好理解.....
二. 参考大神解法....
1. 好吧,和我的思路差不多, 只不过我不是构建新的helper函数进行递归, 直接在原来的函数里面递归.并且将tmp.push_back操作写在前面,可以省略一个我的pop过程.
class Solution {
public:
void helper(TreeNode* root, int sum, vector<vector<int>>& res, vector<int>& tmp) {
if (root == NULL) return;
tmp.push_back(root->val);
if (root->left == NULL&&root->right == NULL&&root->val == sum) {
res.push_back(tmp);
//不需要return,因为执行下去会直接return.
}
helper(root->left, sum - root->val, res, tmp);
helper(root->right, sum - root->val, res, tmp);
tmp.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res;
vector<int> tmp;
helper(root, sum, res, tmp);
return res;
}
};