# Middle-题目64：95. 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

public class Solution {
public List<TreeNode> generateTrees(int n) {
if(n==0) return new ArrayList<TreeNode>();
return generateTrees(1, n);
}

private List<TreeNode> generateTrees(int start, int end){
if(start>end) {
List<TreeNode> list = new ArrayList<TreeNode>();
return list;
}
if(start==end) {
List<TreeNode> list = new ArrayList<TreeNode>();
}
List<TreeNode> roots = new ArrayList<TreeNode>();
for(int i=start;i<=end;i++){
List<TreeNode> leftTrees = generateTrees(start, i-1);
List<TreeNode> rightTrees = generateTrees(i+1, end);
for(int j=0;j<leftTrees.size();j++){
for(int k=0;k<rightTrees.size();k++){
TreeNode root = new TreeNode(i);
root.left = leftTrees.get(j);
root.right = rightTrees.get(k);
}
}

}
return roots;
}
}

2ms,beats 88.62%,众数3ms,53.26%
cmershen的碎碎念：

• 本文已收录于以下专栏：

举报原因： 您举报文章：Middle-题目64：95. Unique Binary Search Trees II 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)