Share my accepted Java solution!


  • 0
    I
    public class Solution {
        ArrayList<List<Integer>> result;
        ArrayList<Integer> path;
        
        public Solution() {
            result = new ArrayList<List<Integer>>();
            path = new ArrayList<Integer>();
        }
        
        public List<List<Integer>> helper(TreeNode root, int sum) {
            path.add(root.val);
            if (root.left == null && root.right == null) {
                if (root.val == sum) {
                    ArrayList<Integer> t = new ArrayList<Integer>();
                    for (Integer i : path) {
                        t.add(i);
                    }
                    result.add(t);
                }
            } else {
                if (root.left != null) {
                    pathSum(root.left, sum - root.val);
                }
                if (root.right != null) {
                    pathSum(root.right, sum - root.val);
                }
            }
            path.remove(path.size()-1);
            return result;
        }
        
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            if (root == null) {
                return result;
            }
            return helper(root, sum);
        }
    }

Log in to reply
 

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