Java 2 ms solution


  • 0
    H
    public class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> resultList = new ArrayList<>();
            if(root==null) return resultList; //null check
            List<Integer> l = new ArrayList<>();
            int tempSum=0;
            pathSumHelper(resultList, root, sum, 0, l);
           
            return resultList;
        }
        
        private void pathSumHelper(List<List<Integer>> rL, TreeNode n, int sum, int tempSum, List<Integer> l){
            if(n==null) return;
            
            tempSum+=n.val;
            l.add(n.val);
            
            if(n.left==null&&n.right==null && tempSum==sum) {rL.add(new ArrayList(l));}
            else{
                pathSumHelper(rL, n.left, sum, tempSum, l); // go left
                pathSumHelper(rL, n.right, sum, tempSum, l); // go right
            }
            
            l.remove(l.size()-1);
            tempSum-=n.val;
        }
    }
    

Log in to reply
 

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