给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
返回:
[ [5,4,11,2], [5,8,4,5] ]
C++
/**
* 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 dfs(TreeNode* root, int sum, int val, vector<int>& tmp, vector<vector<int>>& res)
{
if(NULL==root)
{
return;
}
else
{
val+=root->val;
tmp.push_back(root->val);
if(NULL==root->left && NULL==root->right)
{
if(sum==val)
{
res.push_back(tmp);
}
}
else
{
dfs(root->left,sum,val,tmp,res);
dfs(root->right,sum,val,tmp,res);
}
tmp.pop_back();
val-=root->val;
}
}
vector<vector<int>> pathSum(TreeNode* root, int sum)
{
vector<vector<int>> res;
vector<int> tmp;
if(NULL==root)
{
return res;
}
else
{
dfs(root,sum,0,tmp,res);
return res;
}
}
};
python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def dfs(self,root,val,su,res,tmp):
if root:
if None==root.left and None==root.right:
if su==val+root.val:
res.append(tmp+[root.val])
else:
self.dfs(root.left,val+root.val,su,res,tmp+[root.val])
self.dfs(root.right,val+root.val,su,res,tmp+[root.val])
def pathSum(self, root: TreeNode, su: int) -> List[List[int]]:
res=[]
tmp=[]
if None==root:
return res
else:
self.dfs(root,0,su,res,tmp)
return res