题目:
- 给你二叉树的根节点
root
和一个整数目标和targetSum
,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。叶子节点 是指没有子节点的节点。
示例:
- 输入: r o o t = [ 5 , 4 , 8 , 11 , n u l l , 13 , 4 , 7 , 2 , n u l l , n u l l , 5 , 1 ] , t a r g e t S u m = 22 root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 root=[5,4,8,11,null,13,4,7,2,null,null,5,1],targetSum=22
- 输出: [ [ 5 , 4 , 11 , 2 ] , [ 5 , 8 , 4 , 5 ] ] [[5,4,11,2],[5,8,4,5]] [[5,4,11,2],[5,8,4,5]]
解题思路一:(递归)
- 确定递归函数的参数和返回值:
vector<vector<int>> res;
vector<int> path;
void dfs(TreeNode* cur, int cnt)
- 确定终止条件:
if(!cur->left && !cur->right && cnt == 0){
res.push_back(path);
return;
}
if(!cur->left && !cur->right) return;
- 确定单层递归逻辑: 先序遍历顺序为: 左 − > 中 − > 右 左->中->右 左−>中−>右
if(cur->left){
cnt -= cur->left->val;
path.push_back(cur->left->val);
dfs(cur->left, cnt);
cnt += cur->left->val;
path.pop_back();
}
if(cur->right){
cnt -= cur->right->val;
path.push_back(cur->right->val);
dfs(cur->right, cnt);
cnt += cur->right->val;
path.pop_back();
}
return;
C++版整体代码
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void dfs(TreeNode* cur, int cnt){
if(!cur->left && !cur->right && cnt == 0){
res.push_back(path);
return;
}
if(!cur->left && !cur->right) return;
if(cur->left){
cnt -= cur->left->val;
path.push_back(cur->left->val);
dfs(cur->left, cnt);
cnt += cur->left->val;
path.pop_back();
}
if(cur->right){
cnt -= cur->right->val;
path.push_back(cur->right->val);
dfs(cur->right, cnt);
cnt += cur->right->val;
path.pop_back();
}
return;
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
res.clear(), path.clear();
if(root == NULL) return res;
path.push_back(root->val);
dfs(root, targetSum - root->val);
return res;
}
};