力扣对应题目链接:113. 路径总和 II - 力扣(LeetCode)
核心考点 :简单回溯法的使用。
一、《剑指Offer》对应内容
二、分析题目
这是一个典型的 DFS 回溯的算法,回溯法本质是一个基于 DFS 的穷举的过程。
- 先添加值(待选结果)
- 在判定现有结果是否满足条件(待选结果是否符合条件,是的话就添加结果集)
- DFS(深度优先)
- 回退(检测下一个)
三、代码
//力扣
/**
* 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 {
private:
vector<vector<int>> res;
vector<int> path;
public:
void dfs(TreeNode* root, int targetSum)
{
if(root==nullptr) return;
path.push_back(root->val);
targetSum-=root->val;
if(root->left==nullptr && root->right==nullptr && targetSum==0)
res.push_back(path);
dfs(root->left, targetSum);
dfs(root->right, targetSum);
path.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
dfs(root, targetSum);
return res;
}
};