Unique Binary Search Trees II

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

For example,
Given n = 3, your program should return all 5 unique BST's shown below.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

Backtracing

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;
}

results matching ""

    No results matching ""