题目描述:
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
返回:
[
[5,4,11,2],
[5,8,4,5]
]
方法1:使用先序遍历的递归
主要思路:
(1)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void helper(TreeNode* root,int sum,vector<int>& cur_path,vector<vector<int>>& res){
//终止
if(root==NULL)
return;
//更新当前路径
cur_path.push_back(root->val);
//更新路径和
sum-=root->val;
//若为叶子结点,且路径和此时为0,则当前路径满足要求,故压入结果中,并返回,返回前,复原路径状态
if(root->left==NULL&&root->right==NULL&&sum==0){
res.push_back(cur_path);
cur_path.pop_back();
return;
}
//左右子树递归
helper(root->left,sum,cur_path,res);
helper(root->right,sum,cur_path,res);
//返回当前路径状态
cur_path.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
//存储当前路径
vector<int> cur_path;
//存储满足要求的路径
vector<vector<int>> res;
helper(root,sum,cur_path,res);//搜索路径
return res;
}
};