Why my solution is so slow? It's a common recursion version.

  • 0

    My code was accepted, but the running time is somehow long. I have compared my code with the sample code and I can't figure out why.

    public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int target) {
    return biTreePathSumHelper(root, target, new ArrayList<Integer>(),
    new ArrayList<List<Integer>>(), 0);

    private List<List<Integer>> biTreePathSumHelper(TreeNode root, 
                                                   int target, 
                                                   List<Integer> path,
                                                   paths, int sum) {
        if (root == null) {
            return paths;
        sum += root.val;
        path = new ArrayList<Integer>(path);
        if (root.left == null && root.right == null) {
            if (sum == target) {
            return paths;
        paths = biTreePathSumHelper(root.left, target, path, paths, sum);
        paths = biTreePathSumHelper(root.right, target, path, paths, sum);
        return paths;


Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.