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]]
The extension of the previous question to find out all the results.
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode RI Ght * TreeNode (int x) {val = x;} }*/ Public classSolution {List List=NewArraylist<list<integer>>(); PublicList<list<integer>> pathsum (TreeNode root,intsum) { if(Root = =NULL) returnlist; GetResult (Root,sum,NewArraylist<integer> (), 0); returnlist; } Public voidGetResult (TreeNode root,intSum,list<integer> ans,intPOS) { if(Root = =NULL ) return ; Ans.add (Root.val); if(Sum = =root.val) { if(Root.left = =NULL&& Root.right = =NULL) {ArrayList result=NewArraylist<integer>(); Result.addall (ANS); List.add (result); }} getresult (Root.left,sum-root.val,ans,pos+1); GetResult (Root.right,sum-root.val,ans,pos+1); Ans.remove (POS); return ; }}
Leetcode 113 Path Sum II-----java