【发布时间】:2014-11-09 03:11:06
【问题描述】:
这是一个 leetcode 问题。 “给定一棵二叉树和一个总和,找到所有从根到叶的路径,其中每个路径的总和等于给定的总和。”但是由于时间超过限制,我的代码无法通过测试用例。但是解决方案代码(https://oj.leetcode.com/discuss/15169/14-line-solution-in-java-using-recursion)可以通过测试用例。不知道两个版本号有什么大的区别?
我的代码:
public class Solution {
List<List<Integer>> res = new ArrayList<List<Integer>>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if (root == null)
return res;
List<Integer> t = new ArrayList<Integer>();
has(root, sum, t);
return res;
}
public void has(TreeNode root, int sum, List<Integer> t) {
if (root == null)
return;
if (root.left == null && root.right == null && sum == root.val) {
t.add(root.val);
res.add(t);
return;
}
t.add(root.val);
has(root.right, sum - root.val, t);
has(root.left, sum - root.val, t);
return;
}
}
解决方案:
public class Solution {
public static List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
if(root==null) return list;
if (root.val==sum && root.left==null && root.right==null) {
list.add(new ArrayList<Integer>());
list.get(list.size()-1).add(root.val);
return list;
}
list.addAll(pathSum(root.left, sum-root.val));
list.addAll(pathSum(root.right, sum-root.val));
for(List<Integer> l:list)
l.add(0, root.val);
return list;
}
}
【问题讨论】:
标签: java performance time