二叉树最经典的解法就是采用递归方法,这道题也不例外。下面是AC代码:
1 /** 2 * Given a binary tree and a sum, determine if the tree has 3 * a root-to-leaf path such that adding up all the values along the path equals the given sum. 4 * @param root 5 * @param sum 6 * @return 7 */ 8 public boolean hasPathSum(TreeNode root, int sum){ 9 if(root == null ) 10 return false; 11 return recurPathSum(root,sum,0); 12 } 13 private boolean recurPathSum(TreeNode root, int sum , int curr){ 14 if(root == null) 15 return sum == curr; 16 if(root.left == null && root.right == null) 17 { 18 return curr+root.val==sum; 19 } 20 return (root.left == null ? false :recurPathSum(root.left,sum, curr+root.val)) || 21 (root.right==null ? false : recurPathSum(root.right, sum, curr+root.val)); 22 } 23 /** 24 * Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 25 * @param root 26 * @param sum 27 * @return 28 */ 29 public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum){ 30 ArrayList<ArrayList<Integer>> r = new ArrayList<ArrayList<Integer>>(); 31 if(root == null) 32 return r; 33 recurPathSum(root, sum, 0, new ArrayList<Integer>(), r); 34 return r; 35 } 36 private void recurPathSum(TreeNode root,int sum, int curr, 37 ArrayList<Integer> path, ArrayList<ArrayList<Integer>>paths){ 38 if(root == null){ 39 if(curr == sum) 40 paths.add(path); 41 return; 42 } 43 if(root.left == null && root.right == null){ 44 if(curr + root.val == sum) 45 { 46 path.add(root.val); 47 paths.add(path); 48 } 49 return; 50 } 51 if(root.left != null) 52 { 53 ArrayList<Integer> p = new ArrayList<Integer>(); 54 p.addAll(path); 55 p.add(root.val); 56 recurPathSum(root.left,sum,curr+root.val,p,paths); 57 } 58 if(root.right != null) 59 { 60 ArrayList<Integer> p = new ArrayList<Integer>(); 61 p.addAll(path); 62 p.add(root.val); 63 recurPathSum(root.right,sum,curr+root.val,p,paths); 64 } 65 }