Basic solution using DFS Java 11 ms


  • 0
    M
    public class Solution {
        private List<List<Integer>> list = new ArrayList<>();
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            if(root == null){
                return list;
            }
            findPaths(root, sum, new ArrayList<Integer>());
            return list;
        }
        
        private void findPaths(TreeNode root, int sum, List<Integer> subList){
            if(root == null){
                return;
            }
            if(root.left == null && root.right == null && sum-root.val == 0){
                list.add(subList);
            }
            sum -= root.val;
            subList.add(root.val);
            
            List<Integer> leftList = new ArrayList<>();
            leftList.addAll(subList);
            List<Integer> rightList = new ArrayList<>();
            rightList.addAll(subList);
            
            findPaths(root.left, sum, leftList);
            findPaths(root.right, sum, rightList);
        }
    }
    

Log in to reply
 

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