Problem Description: Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.
Solution: 递归。
1 public List<List<Integer>> pathSum(TreeNode root, int sum) { 2 List<List<Integer>> list = new ArrayList<List<Integer>>(); 3 if (root == null) return list; 4 List<Integer> tmp = new ArrayList<Integer>(); 5 path(root, sum, list, tmp); 6 return list; 7 } 8 public void path(TreeNode root, int sum, List<List<Integer>> list, List<Integer> tmp) { 9 if (root == null) return; 10 tmp.add(root.val); 11 int leftsum = sum - root.val; 12 13 if (leftsum == 0 && root.left == null && root.right == null) { 14 list.add(new ArrayList<Integer>(tmp)); 15 } 16 path(root.left, leftsum, list, tmp); 17 path(root.right, leftsum, list, tmp); 18 19 tmp.remove(tmp.size() - 1); 20 }
Problem Path Sum II
时间: 2024-11-05 18:43:28