Unique Binary Search Trees II

https://leetcode.com/problems/unique-binary-search-trees-ii/
给定一个正整数,求出1~n的所有正整数能组成的BST组合

   public List generateTrees2(int n) {
        List res = new ArrayList();
        if (n == 0) {
            return res;
        }
        res = generateTrees2Helper(1, n);
        return res;
    }

    public List generateTrees2Helper(int left, int right) {
        List res = new ArrayList();

        if (left > right) {
            res.add(null);
            return res;
        }
        for (int i = left; i <= right; i++) {
            List leftList = generateTrees2Helper(left, i - 1);
            List rightList = generateTrees2Helper(i + 1, right);
            for (int j = 0; j < leftList.size(); j++) {
                for (int k = 0; k < rightList.size(); k++) {
                    TreeNode root = new TreeNode(i);
                    root.left = leftList.get(j);
                    root.right = rightList.get(k);
                    res.add(root);
                }
            }
        }
        return res;
    }

你可能感兴趣的:(Unique Binary Search Trees II)