Topic:
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 sum = 22
and,
5 / 4 8 / / / 4 / \ / 7 2 5 1
Return
[ [5,4,11,2], [5,8,4,5]]
Exercises
In addition to judging whether there is such a path sum, you also need to return all the possibility results, so we use the traditional DFS recursion to solve the sub-problem. The code is as follows:
1 Public voidPathsumhelper (TreeNode root,intSum, List <Integer> sumlist, list<list<integer>>pathlist) {2 if(root==NULL) 3 return;4 Sumlist.add (root.val);5sum = sum-Root.val;6 if(root.left==NULL&& root.right==NULL){7 if(sum==0){8Pathlist.add (NewArraylist<integer>(sumlist));9 }Ten}Else{ One if(root.left!=NULL) A Pathsumhelper (root.left,sum,sumlist,pathlist); - if(root.right!=NULL) - Pathsumhelper (root.right,sum,sumlist,pathlist); the } -Sumlist.remove (Sumlist.size ()-1); - } - + PublicList<list<integer>> pathsum (TreeNode root,intsum) { -List<list<integer>> pathlist=NewArraylist<list<integer>>(); +List<integer> sumlist =NewArraylist<integer>(); A Pathsumhelper (root,sum,sumlist,pathlist); at returnpathlist; -}
Reference:http://www.cnblogs.com/springfor/p/3879827.html
*path Sum II