Java solution. 7ms


  • 0
    F

    This is My solution. Hope will help.

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            
            List<List<Integer>> ret = new ArrayList<>();
            
            List<Integer> subset = new ArrayList<Integer>();
            
            pathSumHelper(root,sum,subset,ret);
            
            return ret;
        }
        
        public void pathSumHelper(TreeNode root, int sum, List<Integer> subset,List<List<Integer>> ret){
    
            if (root == null){
                return;
            }
            
            subset.add(root.val);
            
            if ( sum == root.val && root.left == null && root.right == null){
                ret.add(subset);
                return;
            }
            
    
            pathSumHelper(root.left,sum - root.val,new ArrayList<>(subset),ret);
            pathSumHelper(root.right,sum - root.val,new ArrayList<>(subset),ret);
            
        }
    }
    

Log in to reply
 

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