My recursive solution with a dash of Java 8


  • 0
    N
    public List<List<Integer>> pathSum(TreeNode root, int sum)
    {
        List<List<Integer>> answer = new ArrayList<>();
        if (root != null)
        {
            if (root.left == null && root.right == null)
            {
                if (sum == root.val)
                {
                    List<Integer> list = new ArrayList<Integer>();
                    list.add(root.val);
                    answer.add(list);
                }
            }
            else 
            {
                List<List<Integer>> leftAnswer = pathSum(root.left, sum - root.val);
                leftAnswer.forEach(l -> l.add(0, root.val));
                answer.addAll(leftAnswer);
    
                List<List<Integer>> rightAnswer = pathSum(root.right, sum - root.val);
                rightAnswer.forEach(l -> l.add(0, root.val));
                answer.addAll(rightAnswer);
            }
        }
        return answer;
    }

Log in to reply
 

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