本人电子系,只为一学生。心喜计算机,小编以怡情。
好久没写代码,结果惨不忍睹,只提供参考。
static public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
// Write your code here
List<List<Integer>> ret=new ArrayList<>();
ArrayList<Integer> linshi=new ArrayList<>();
int sum=root.val;
preordertravel(root,ret,target,linshi,sum);
return ret;
}
static void preordertravel(TreeNode root,List<List<Integer>> ret,int target,ArrayList<Integer> linshi,int sum)
{
if(sum==target&&root!=null&&root.left==null&&root.right==null)
{
linshi.add(root.val);
ret.add(new ArrayList<>(linshi));
linshi.remove(linshi.size()-1);
}
else {
if(root!=null) {
linshi.add(root.val);
preordertravel(root.left, ret, target, linshi, root.left==null?sum:sum+root.left.val);
preordertravel(root.right, ret, target, linshi, root.right==null?sum:sum+root.right.val);
linshi.remove(linshi.size()-1);
}
}
}