Clean Java Recursive Solution

  • 1
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
    		List<List<Integer>> ans = new LinkedList<List<Integer>>();
    		if (root == null)
    			return ans;
    		pathSumHelper(root, ans, new LinkedList<Integer>(), sum);
    		return ans;
    	private void pathSumHelper(TreeNode root, List<List<Integer>> ans,
    			LinkedList<Integer> curAns, int sum) {
    		LinkedList<Integer> newCur = new LinkedList<Integer>(curAns);
    		if (root.left == null && root.right == null) {
    			if (sum == root.val)
    		if (root.left != null)
    			pathSumHelper(root.left, ans, newCur, sum - root.val);
    		if (root.right != null)
    			pathSumHelper(root.right, ans, newCur, sum - root.val);

  • 0

    I solved the problem in the same way, but I got a time limited exceeded issue.
    So you didn't get this problem?

  • 0

    Yes, this solution got AC. You can post your codes here if you like and lets see why it's different~

Log in to reply

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