Java - As simple as it can get


  • 0
    T
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> result = new ArrayList<>();
            if(root == null) return result;
            
            helper(root,sum, result, new ArrayList<Integer>());
            return result;
        }
        
        private void helper(TreeNode root, int sum, List<List<Integer>> result, List<Integer> list){
            if(root == null) return;
            if(root.left == null && root.right == null){
                if(sum == root.val){
                    
                    List<Integer> temp = new ArrayList<>(list);
                    temp.add(root.val);
                    result.add(temp);
                }
                return;
            }
            
            list.add(root.val);
            helper(root.left, sum-root.val, result,list );
            helper(root.right,sum-root.val,result,list);
            list.remove(list.size()-1);
        }
    }
    

    Let me know if you have any questions.


Log in to reply
 

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