Path Sum II
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 / / / 4 / \ / 7 2 5 1
Return
[ [5,4,11,2], [5,8,4,5]]
This problem is not own a out, looked at the discuss area inside, but the writing is really beautiful
1 Packagecom.gxf.test;2 3 Importjava.util.ArrayList;4 Importjava.util.List;5 ImportJava.util.Stack;6 7 8 9 classTreeNode {Ten intVal; One TreeNode left; A TreeNode right; -TreeNode (intX) {val =x;} - } the - Public classSolution { - PublicList<list<integer>> pathsum (TreeNode root,intsum) { -list<list<integer>> result =NewArraylist<list<integer>>(); + if(NULL==root) - returnresult; + if(NULL= = Root.left &&NULL= = Root.right) {//leaf knot Point A if(Root.val = =sum) { atlist<integer> element =NewArraylist<integer>(); - element.add (sum); - Result.add (element); - } -}Else{ -result = Pathsum (Root.left, sum-root.val);//get all the paths to the left subtree inlist<list<integer>> result_right = Pathsum (Root.right, sum-root.val);//get all paths to right subtree - Result.addall (result_right); to + for(list<integer>Element:result) { -Element.add (0, Root.val);//Add the root node to the first location the } * } $ Panax Notoginseng returnresult; - } the}
Another type of Dfs
1 Packagecom.gxf.test;2 3 Importjava.util.ArrayList;4 Importjava.util.List;5 ImportJava.util.Stack;6 7 8 9 classTreeNode {Ten intVal; One TreeNode left; A TreeNode right; -TreeNode (intX) {val =x;} - } the - Public classSolution { - PublicList<list<integer>> pathsum (TreeNode root,intsum) { -list<list<integer>> result =NewArraylist<list<integer>>(); +List<integer> currentelement =NewArraylist<integer>(); - + GetPath (root, Sum, result, currentelement); A at returnresult; - } - - /** - * Recursive get result - * @paramRoot in * @paramsum - * @paramreuslt to * @paramCurrentresult + */ - Public voidGetPath (TreeNode root,intSum, list<list<integer>> result, list<integer>Currentresult) { the if(NULL==root) * return; $Currentresult.add (Root.val);//Add to CurrentresultPanax Notoginseng if(NULL= = Root.left &&NULL= = Root.right) {//leaf knot Point - if(Sum = =root.val) { theResult.add (NewArraylist<integer> (Currentresult));//Add to result + } ACurrentresult.remove (Currentresult.size ()-1);//Remove the leaf nodes. the return ; + } - Else{//non-leaf knot point $GetPath (Root.left, Sum-root.val, result, Currentresult);//traversing the left sub-tree $GetPath (Root.right, Sum-root.val, result, Currentresult);//traversing the right sub-tree - - } the -Currentresult.remove (Currentresult.size ()-1);//when the recursion is returned, none of this will delete the leaf node.Wuyi } the}
Path Sum II