My recursive accepted consise java solution


  • 0
    M
    public class Solution {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
    
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            if(root == null) {
                return result;
            }
            List<Integer> pathSoFar = new ArrayList<Integer>();
            pathSumList(root, sum, pathSoFar);
            return result;
        }
    
        private void pathSumList(TreeNode root, int sum, List<Integer> pathSoFar) {
            if(root == null) {
                return;
            }
            pathSoFar.add(root.val);
            if(root.val == sum && root.left == null && root.right == null) {
                result.add(new ArrayList<Integer>(pathSoFar));
            }
            else {
                pathSumList(root.left, sum - root.val, pathSoFar);
                pathSumList(root.right, sum - root.val, pathSoFar);
            }
            //Remove the element since call is returning one level up
            pathSoFar.remove(pathSoFar.size() - 1);
        }
    }
    

    The idea is to keep passing the path traversed so far down to each leaf node. If sum is achieved then add the path to the result.


  • 0
    M

    What is the runtime of this solution?


Log in to reply
 

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