Unique Binary Search Trees II

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

Example:

Input: 3
Output:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:

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

Constraints:

  • 0 <= n <= 8

public class Solution {
    public static List<TreeNode> generateTrees(int N) {
        List<TreeNode>[] result = new List[N + 1];
        // result[i] -> stores BSTs with first i nodes
        result[0] = new ArrayList<TreeNode>();
        if (N == 0)
            return result[0];
        // Adding null for calulations later
        result[0].add(null);
        // Starting with 1 node
        for (int n = 1; n <= N; n++) {
            result[n] = new ArrayList<TreeNode>();
            // Consider all the nodes from 1 -> n, as root
            for (int j = 1; j <= n; j++) {
                // Forming all the combinations with different left and right childs
                for (TreeNode nodeL : result[j - 1]) {
                    for (TreeNode nodeR : result[n - j]) {
                        TreeNode node = new TreeNode(j);
                        // The left tree will have correct stucture and values
                        node.left = nodeL;
                        // But the right tree will have correct structure but
                        // but all the values will be offset by "j"
                        node.right = clone(nodeR, j);
                        result[n].add(node);
                    }
                }
            }
        }
        return result[N];
    }

    private static TreeNode clone(TreeNode n, int offset) {
        if (n == null) {
            return null;
        }
        TreeNode node = new TreeNode(n.val + offset);
        node.left = clone(n.left, offset);
        node.right = clone(n.right, offset);
        return node;
    }
}

Last updated