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 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 ArrayList<ArrayList<Integer>> result = null; 12 public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { 13 // IMPORTANT: Please reset any member data you declared, as 14 // the same Solution instance will be reused for each test case. 15 result = new ArrayList<ArrayList<Integer>>(); 16 check(root, sum, new ArrayList<Integer>()); 17 return result; 18 } 19 public void check(TreeNode root, int sum, ArrayList<Integer> row){ 20 if(root == null) return; 21 row.add(root.val); 22 sum -= root.val; 23 if(root.left == null && root.right == null){ 24 if(sum == 0) 25 result.add(row); 26 return; 27 } 28 check(root.left , sum, new ArrayList<Integer>(row)); 29 check(root.right, sum, new ArrayList<Integer>(row)); 30 } 31 }
posted on 2013-11-16 09:06 Step-BY-Step 阅读(166) 评论(0) 编辑 收藏 举报