简单题。现在对于这种递归已经很熟练了啊。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public ArrayList> pathSum(TreeNode root, int sum) { // Start typing your Java solution below // DO NOT write main() function ArrayList > ret = new ArrayList >(); ArrayList arr = new ArrayList (); PathSum(root, sum, arr, ret); return ret; } public void PathSum(TreeNode root, int sum, ArrayList arr, ArrayList > ans) { if (root == null) return; if (root.left == null && root.right == null && root.val == sum) { arr.add(root.val); ArrayList tmp = new ArrayList (); for (int i = 0; i < arr.size(); i++) { tmp.add(arr.get(i)); } ans.add(tmp); arr.remove(arr.size() - 1); } else { arr.add(root.val); PathSum(root.left, sum - root.val, arr, ans); arr.remove(arr.size() - 1); arr.add(root.val); PathSum(root.right, sum - root.val, arr, ans); arr.remove(arr.size() - 1); } }}