样例
给定一个二叉树,和 目标值 = 5
:
1
/ \
2 4
/ \
2 3
返回:
[
[1, 2, 2],
[1, 4]
]
解法:DFS,注意路径和的概念,要到叶子节点
AC代码:
class Solution {
public:
/*
* @param root: the root of binary tree
* @param target: An integer
* @return: all valid paths
*/
vector<vector<int>> binaryTreePathSum(TreeNode * root, int target) {
// write your code here
vector<vector<int>> res;
if(!root){
return res;
}
vector<int> a;
TreePathSum(root, target, 0, a, res);
return res;
}
void TreePathSum(TreeNode * root, int target,int now, vector<int>& a, vector<vector<int>> &res) {
// write your code here
now += root->val;
a.push_back(root->val);
if(now == target){
if(!root->right && !root->left )
res.push_back(a);
}
if(root->left){
TreePathSum(root->left, target, now, a, res);
a.pop_back();
}
if(root->right){
TreePathSum(root->right, target, now, a, res);
a.pop_back();
}
return ;
}
};