Given an integer 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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; left = null; right = null; }
* }
*/
public class Solution {
public List<TreeNode> generateTrees(int m, int n){
List<TreeNode> ans = new LinkedList<TreeNode>();
if(m > n){
ans.add(null);
}
for(int i = m; i<=n; i++){
List<TreeNode> leftTrees = generateTrees(m, i-1);
List<TreeNode> rightTrees = generateTrees(i+1, n);
for(TreeNode left: leftTrees){
for(TreeNode right: rightTrees){
TreeNode root = new TreeNode(i);
root.left = left;
root.right = right;
ans.add(root);
}
}
}
return ans;
}
public List<TreeNode> generateTrees(int n) {
return generateTrees(1, n);
}
}