Simple java solution, 2 ms


  • 0
    
    public class Solution {
        public  List<List<Integer>> pathSum(TreeNode root, int sum) {
    
            if(root==null){
                return new ArrayList<List<Integer>>();
            }
    
            List<List<Integer>> result = new ArrayList<List<Integer>>();
    
            pathSum(root, new ArrayList<Integer>(), sum, result);
    
            return result;
        }
    
        private  void pathSum(TreeNode node, List<Integer> list, int sum,  List<List<Integer>> result){
            if(node == null){
                return;
            }
            boolean isLeaf = (node.left == null && node.right == null);
            int val = node.val;
            list.add(val);
            if(val == sum && isLeaf){
                List<Integer> oneResult  = new ArrayList<Integer>();
                oneResult.addAll(list);
                result.add(oneResult);
            } else {
                pathSum(node.left, list, sum - val, result);
                pathSum(node.right, list, sum - val, result);
            }
    
            list.remove(list.size() - 1);
        }
    
    
    }
    

Log in to reply
 

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