# 路径总和 II

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。

示例 1:

输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22

输出:[[5,4,11,2],[5,8,4,5]]

示例 2:

输入:root = [1,2,3], targetSum = 5

输出:[]

示例 3:

输入:root = [1,2], targetSum = 0

输出:[]

提示:

以下错误的选项是?

## aop ### before ```c #include using namespace std; 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) {} }; ``` ### after ```c ``` ## 答案 ```c class Solution { public: vector> pathSum(TreeNode *root, int sum) { int pos = 0; vector path; vector> result; dfs(root, sum, pos, path, result); return result; } private: void dfs(TreeNode *root, int sum, int &pos, vector &path, vector> &result) { if (root == NULL) return; pos += root->val; path.push_back(root->val); if (!root->left && !root->right && pos == sum) result.push_back(path); dfs(root->left, sum, pos, path, result); dfs(root->right, sum, pos, path, result); path.pop_back(); } }; ``` ## 选项 ### A ```c class Solution { public: void find(TreeNode *node, vector> &result, vector &path, int sum) { path.push_back(node->val); if (node->left == NULL && node->right == NULL && sum == node->val) { result.push_back(path); return; } if (node->left != NULL) { find(node->left, result, path, sum - node->val); path.pop_back(); } if (node->right != NULL) { find(node->right, result, path, sum - node->val); path.pop_back(); } } vector> pathSum(TreeNode *root, int sum) { vector> result; vector path; if (root == NULL) { return result; } find(root, result, path, sum); return result; } }; ``` ### B ```c class Solution { public: vector> pathSum(TreeNode *root, int sum) { vector> res; if (!root) return res; vector temp; dfs(root, res, temp, sum); return res; } void dfs(TreeNode *root, vector> &res, vector temp, int sum) { temp.push_back(root->val); if (!root->left && !root->right && 0 == sum - root->val) res.push_back(temp); if (root->left) dfs(root->left, res, temp, sum - root->val); if (root->right) dfs(root->right, res, temp, sum - root->val); } }; ``` ### C ```c class Solution { public: vector> pathSum(TreeNode *root, int targetSum) { DFS(root, targetSum); return result; } void DFS(TreeNode *root, int targetSum) { if (root == nullptr) return; tmp_path.emplace_back(root->val); targetSum -= root->val; if (root->left == nullptr && root->right == nullptr && targetSum == 0) { result.emplace_back(tmp_path); } DFS(root->left, targetSum); DFS(root->right, targetSum); tmp_path.pop_back(); } private: vector> result; vector tmp_path; }; ```