Exactly same input works in eclipse but not here?


  • 0
    F
    public class Solution {
        public ArrayList<TreeNode> generateTrees(int n) { 
            if(n == 0) {
                ArrayList<TreeNode> roots = new ArrayList<TreeNode>();
                roots.add(null);
    			return roots;
            }
    		
    		return generateSubTree(1,n);
    	}
    	
    	//this function should return the root array of all possible subLeftTree
    	public ArrayList<TreeNode> generateSubTree(int subtree_start, int subtree_end){
            ArrayList<TreeNode> subTreeRoots = new ArrayList<TreeNode>();
    		
    		if( subtree_start > subtree_end)
    		    return subTreeRoots;
    		    
    		if( subtree_start == subtree_end) {
    			TreeNode subRoot = new TreeNode(subtree_end);
    			subTreeRoots.add(subRoot);
    			return subTreeRoots;
    		}
    		
    		for(int i=subtree_start;i<=subtree_end;i++) {
    			ArrayList<TreeNode> leftTreeRoots = generateSubTree(subtree_start+1,i-1);
    			ArrayList<TreeNode> rightTreeRoots = generateSubTree(i+1,subtree_end);
    
    			//only left subtree
    			if(leftTreeRoots.size() != 0 && rightTreeRoots.size() == 0) {
    				for(int j = 0;j<leftTreeRoots.size();j++) {
    					TreeNode subRoot = new TreeNode(i);
    					subRoot.left = leftTreeRoots.get(j);
    					subTreeRoots.add(subRoot);
    				}
    			} else if(leftTreeRoots.size() == 0 && rightTreeRoots.size() != 0){ //only right subtree
    				for(int j = 0;j<rightTreeRoots.size();j++) {
    					TreeNode subRoot = new TreeNode(i);
    					subRoot.right = rightTreeRoots.get(j);
    					subTreeRoots.add(subRoot);
    				}
    			} else { // left and right subtree both exists, all combinations
    				for(int j = 0;j<leftTreeRoots.size();j++) {
    					for(int k = 0;k<rightTreeRoots.size();k++) {
    						TreeNode subRoot = new TreeNode(i);
    						subRoot.left = leftTreeRoots.get(j);
    						subRoot.right = rightTreeRoots.get(k);
    						subTreeRoots.add(subRoot);
    					}
    				}
    			}
    		}
    		
    		return subTreeRoots;
        }
    }
    

    from Leetcode OJ, I got this error message: when input is 2, expected to return {[1,#,2],[2,1]} and my code returns only {[1,#,2]}. Which is not true, coz I run on eclipse, i got both trees printed out..


  • 0
    M

    I believe that your eclipse and leetcode solutions differ slightly.

    ArrayList<TreeNode> leftTreeRoots = generateSubTree(subtree_start+1,i-1);
    

    You are cutting the section by 1 off both ends. Change to:

    ArrayList<TreeNode> leftTreeRoots = generateSubTree(subtree_start,i-1);
    

    and it will start working.


Log in to reply
 

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