给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值
的路径。
一个有效的路径,指的是从根节点到叶节点的路径。
样例
给定一个二叉树,和 目标值 = 5
:
1
/ \
2 4
/ \
2 3
返回:
[
[1, 2, 2],
[1, 4]
]
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of binary tree
* @param target an integer
* @return all valid paths
*/
vector<vector<int>> Sum;//全局变量,要返回的值
vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {
if(root==NULL){
return Sum;
}
int currentSum=0;
vector<int> path;
Path(root,target,path,currentSum);
return Sum;
}
void Path(TreeNode *root, int target,vector<int> path,int currentSum)
{
currentSum += root->val;
path.push_back(root->val);
//如果是叶结点,且路径上的结点值等于target,打印出来
bool isLeaf = root->left == NULL && root->right == NULL;
if(currentSum==target&&isLeaf){
Sum.push_back(path);
}
//如果不是叶结点,则遍历它的子结点
if(root->left!=NULL){
Path(root->left,target,path,currentSum);
}
if(root->right!=NULL){
Path(root->right,target,path,currentSum);
}
//在返回到父结点之前,在路径上删除当前结点,并在currentSum中减去该结点值
currentSum -= root->val;
path.pop_back();
}
};