问题描写叙述:
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 andsum = 22
, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5]]
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public List
> pathSum(TreeNode root, int sum) { if(root == null) return new ArrayList(); List
> result = new LinkedList
>(); List list = new LinkedList (); getPathNum(root, sum,list,result); return result; } public void getPathNum(TreeNode root, int sum,List list,List
> result){ if(root.left == null && root.right ==null){ if(sum == root.val){ List tmp = new LinkedList (list); tmp.add(root.val); result.add(tmp); return; } else return; } list.add(root.val); List ltmp = new LinkedList (list); List rtmp = new LinkedList (list); if(root.left !=null) getPathNum(root.left, sum-root.val,ltmp,result); if(root.right !=null) getPathNum(root.right, sum-root.val,rtmp, result); }