Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:Given the below binary tree and
sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
java版:
class TreeNode{
int val;
TreeNode left=null;
TreeNode right=null;
void TreeNode(int val){
this.val=val;
}
}
public class PathSumII{
public List<List<Integer>> reslove(int target,TreeNode root){
List<List<Integer>> list=new ArrayList<List<Integer>>();
List<Integer> sub=new ArrayList<Integer>();
dfs(root,target,list,sub);
return list;
}
public void dfs(TreeNode root,int target,List<List<Integer>> list,List<Integer> sub){
if(root==null){
return
}
if(root.left==null && root.right==null && root.val=target){
sub.add(root.val);
list.add(sub);
}
dfs(root.left,target-root.val,list,sub);
dfs(root.right,target-root.val,list,sub);
}
Python:
#coding:utf-8
class TreeNode:
def __init__(self,val,left,ruigh):
self.val=val
self.right=right
self.left=left
class Solution:
def pathsumii(self,root,target):
ans=[]
dfs(root,ans,[],target)
return ans
def dfs(self,root,ans,sub,target):
if not root:
return
if root.left==None and root.right and root.val==target:
ans.append(sub+[root.val])
dfs(root.left,ans,sub+[root.val],target-root.val)
dfs(root.right,ans,sub+[root.val],target-root.val)