标签:solution turn href ref 回溯 题目 alt tar null
前序遍历+回溯
代码参考:https://leetcode-cn.com/problems/path-sum-ii/solution/cqian-xu-bian-li-jia-hui-su-by-qing-feng-seve/
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<vector<int>> ans;
vector<int> cur;
dfs( root, ans,cur,targetSum );
return ans;
}
void dfs( TreeNode* root, vector<vector<int>> &ans, vector<int >& cur,int &targetSum ){
if( root == nullptr ){
return;
}
targetSum -= root->val;//别写成了+= 泪目
cur.push_back(root->val);//对节点的处理写在前面是为了下面判断条件统一,不过这样有一个后果:因为回溯算法有加入必须有退出,所以再cur调用pop之前不能return!
if( targetSum == 0 && root ->left==nullptr && root -> right == nullptr){//当前已计入
ans.push_back(cur);//所以这里后面不要跟return
}
dfs( root->left, ans, cur, targetSum );
dfs( root->right, ans, cur, targetSum );
targetSum +=root->val;//这里,前序遍历,两个递归后面写一个回溯就够了
cur.pop_back();
}
};
标签:solution turn href ref 回溯 题目 alt tar null
原文地址:https://www.cnblogs.com/lzyrookie/p/14698531.html