My accepted java code (DFS)


  • 0
    X

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> cur = new ArrayList<>();
    helper(root, sum, cur, result);
    return result;
    }
    public void helper(TreeNode root, int sum, List<Integer> cur, List<List<Integer>> result){
    //base case

        	if(root == null){
                return;
            }
            
            
            if(root.left == null && root.right == null){
                if(sum == root.val){
                    cur.add(root.val);
                    result.add(new ArrayList(cur));
                    cur.remove(cur.size() - 1);
                    return;
                }
                return;
            }
            cur.add(root.val);
            sum = sum - root.val;
            helper(root.left, sum, cur, result);
            helper(root.right, sum, cur, result);
            cur.remove(cur.size() - 1);
            
        }

Log in to reply
 

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