Easy and Clean java solution


  • 0
    M
    public class Solution {
        List<List<Integer>> li;
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            li = new LinkedList<List<Integer>>();
            if(root==null){
                return li;
            }
            calculateSum(root,new LinkedList<Integer>(),0,sum);
            return li;
        }
        public void calculateSum(TreeNode root, List<Integer> l, int sumsofar, int sum){
            if(sum==sumsofar && root==null){
                
                li.add(new LinkedList<Integer>(l));
            }
            if(root==null){
                return;
            }
            l.add(root.val);
            if(root.left==null && root.right==null){
                //Indicates that this is a root node. Only if both the left and right subtrees are null we calculate the sum.
                calculateSum(root.left,l,sumsofar+root.val,sum);
            }else{
                //To avoid adding to the list when it's not a leaf node. 
                if(root.left!=null)
                calculateSum(root.left,l,sumsofar+root.val,sum);
                if(root.right!=null)
                calculateSum(root.right,l,sumsofar+root.val,sum);    
            }
            
            l.remove(l.size()-1);
        }
    }
    

Log in to reply
 

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