Unique Binary Search Trees
Given A, generate all structurally unique BST’s (binary search trees) that store values 1…A.
Input Format:
The first and the only argument of input contains the integer, A.
Output Format:
Return a list of tree nodes representing the generated BST's.
Constraints:
1 <= A <= 15
Example:
Input 1:
A = 3
Output 1:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
Solution:
/**
* Definition for binary tree
* class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private TreeNode copy(TreeNode a, int val) {
if (a == null) return null;
TreeNode t = new TreeNode(a.val + val);
if (a.left != null) {
t.left = copy(a.left, val);
}
if (a.right != null) {
t.right = copy(a.right, val);
}
return t;
}
public ArrayList<TreeNode> generateTrees(int a) {
// dp[i] = list of treenode for i
// dp[i] = dp[j - 1] * dp[i - j] for j <= i
// dp[0] = empty list, dp[1] = list(1)
// dp[a]
ArrayList<TreeNode>[] dp = new ArrayList[a + 1];
dp[0] = new ArrayList<TreeNode>();
dp[0].add(null);
dp[1] = new ArrayList<TreeNode>();
dp[1].add(new TreeNode(1));
for (int i = 2; i <= a; i ++) {
dp[i] = new ArrayList<TreeNode>();
for (int j = 1; j <= i; j ++) {
for (int k = 0; k < dp[j - 1].size(); k ++) {
for (int p = 0; p < dp[i - j].size(); p ++) {
TreeNode root = new TreeNode(j);
root.left = copy(dp[j - 1].get(k), 0);
root.right = copy(dp[i - j].get(p), j);
dp[i].add(root);
}
}
}
}
return dp[a];
}
}