一、题目描述:
二、思路分析:
刚说回溯就是对搜索树的dfs
还真的出了个dfs
这道题最开始我是在node == null 时判断并添加path到res
但我发现比如第二个叶子节点,left和right 都是NULL,这样的话同样的数就会出现两次
“那你set去重不就行了吗”
不行!因为res这的可以有一模一样的path,也就是他需要重复
三、AC 代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<int> path;
vector<vector<int>> res;
if(root == NULL)return res;
dfs(root, path,res,0, targetSum);
// set<vector<int>> st(res.begin(), res.end());
// res.assign(st.begin(), st.end());
return res;
}
void dfs(TreeNode* node, vector<int> path,vector<vector<int>>& res, int sum, int targetSum){
if(node == NULL){
return;
}
// if(node->val + sum > targetSum)return;
sum = node->val + sum;
path.push_back(node->val);
if(node->left == NULL && node -> right == NULL){
if(sum == targetSum){
res.push_back(path);
}
}
dfs(node->left, path,res,sum, targetSum);
dfs(node->right, path,res,sum, targetSum);
return;
}
};
四、总结:
本来这题还想做个剪枝,sum>target就直接return
结果这题树上有负数, 画蛇添足了
本文正在参与「掘金 2021 春招闯关活动」, 点击查看 活动详情