Java 2ms solution beats 92%


  • 4
    H
    /**
     * 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<TreeNode> generateTrees(int n) {
            if(n==0) return new ArrayList<TreeNode>();
            return generateTress(1, n);
        }
        
        private List<TreeNode> generateTress(int start, int end){
            if(start>end) {
                List<TreeNode> list = new ArrayList<TreeNode>();
                list.add(null);
                return list;
            }
            if(start==end) {
                List<TreeNode> list = new ArrayList<TreeNode>();
                list.add(new TreeNode(start)); return list;
            }
            List<TreeNode> roots = new ArrayList<TreeNode>();
            for(int i=start;i<=end;i++){
                List<TreeNode> leftTrees = generateTress(start, i-1);
                List<TreeNode> rightTrees = generateTress(i+1, end);
                for(int j=0;j<leftTrees.size();j++){
                    for(int k=0;k<rightTrees.size();k++){
                        TreeNode root = new TreeNode(i);
                        root.left = leftTrees.get(j);
                        root.right = rightTrees.get(k);
                        roots.add(root);
                    }
                }
                
            }
            return roots;
        }
    }

  • 0
    B

    What is the complexity may I ask?

    I suppose it to be O(number of solutions), but how to express it with "n" ?


  • 0
    A

    You can try memory search. Actually we do a lot of duplicate computation in this solution


Log in to reply
 

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