一、题目
1、题目描述
给你二叉树的根节点 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
输出:[]
2、基础框架
/**
* 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) {
}
};
3、原题链接
二、解题报告
1、代码详解
/**
* 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<int> copy(vector<int> &path) {
vector<int> ans;
for (int num : path) {
ans.push_back(num);
}
return ans;
}
void process(TreeNode *root, vector<int> &path, int preSum, int sum, vector<vector<int>> &ans) {
if (root->left == nullptr && root->right == nullptr) {
if (preSum + root->val == sum) {
path.push_back(root->val);
ans.push_back(copy(path)); //一定要加入拷贝的path,因为path后续会被修改
path.pop_back(); //删除最后一个元素,恢复到之前的状态,以便往另一条路径试探
}
return ;
}
path.push_back(root->val);
preSum += root->val;
if (root->left != nullptr) {
process(root->left, path, preSum, sum, ans);
}
if (root->right != nullptr) {
process(root->right, path, preSum, sum, ans);
}
path.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<vector<int>> ans;
if (root == nullptr) return ans;
vector<int> path;
process(root, path, 0, targetSum, ans);
return ans;
}
};