My java solution 208ms


  • 0
    R
    public List<TreeNode> generateTrees(int n) {
        return generateTrees(1, n);
    }
    
    private List<TreeNode> generateTrees(int b, int e) {
        List<TreeNode> res = new ArrayList<>();
        if (b > e) {
            res.add(null);
        } else if (b == e) {
            res.add(new TreeNode(b));
        } else {
            for (int i = b; i <= e; i++) {
                List<TreeNode> left = generateTrees(b, i - 1);
                List<TreeNode> right = generateTrees(i + 1, e);
                int lsize = left.size();
                int rsize = right.size();
                for (int j = 0; j < lsize; j++) {
                    for (int k = 0; k < rsize; k++) {
                        TreeNode root = new TreeNode(i);
                        root.left = left.get(j);
                        root.right = right.get(k);
                        res.add(root);
                    }
                }
            }
        }
    
        return res;
    }

Log in to reply
 

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