递归,用一个vector存储中间的path路径。
#include <vector>
class Solution {
public:
// 一个存放最后结果,一个存放临时结果
vector<vector<int>> res;
vector<int> path;
void dfs(TreeNode* root, int target, int temp){
if(root == nullptr) return;
path.emplace_back(root->val);
if(root->left == nullptr && root->right == nullptr && root->val + temp == target){
res.emplace_back(path);
}
dfs(root->left, target, temp + root->val);
dfs(root->right, target, temp + root->val);
path.pop_back();
}
vector<vector<int> > FindPath(TreeNode* root, int target) {
if(root == nullptr) return {};
dfs(root, target, 0);
return res;
}
};
- 时间复杂度:O(n^2),其中n是树的节点数。
- 空间复杂度:O(n),递归栈的深度不会超过节点数量,但最大可能就是节点数量。