题目链接:不同的二叉搜索树II
题目描述:
给定一个整数 n,生成所有由 1 … n 为节点所组成的 二叉搜索树 。
示例:
输入:3
输出:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
解释:
以上的输出对应以下 5 种不同结构的二叉搜索树:
以上的输出对应以下 5 种不同结构的二叉搜索树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
题目分析:二叉搜索树的特点:左子树均比根节点小,右子树均比根节点大,根据这个特点建树。
[1,n]是从小到大排好的,我们只要选择任意一个点作为根节点,然后对其两边的数递归建树
代码:
class Solution {
public List<TreeNode> generateTrees(int n) {
if(n == 0) return new ArrayList<>();
return return buildTree(1,n);
}
public List<TreeNode> buildTree(int l,int r) {
List<TreeNode> res = new ArrayList<>();
if(l>r){
res.add(null);
return res;
}
for (int i = l; i <= r; i++) {
List<TreeNode> left = buildTree(l, i-1);
List<TreeNode> right = buildTree(i+1, r);
for (TreeNode tn1 : left) {
for (TreeNode tn2 : right) {
TreeNode cur = new TreeNode(i);
cur.left = tn1;
cur.right = tn2;
res.add(cur);
}
}
}
return res;
}
}
补充 不同二叉树I
分析:这个题其实用到一个数学知识,卡特兰数,这个我之前是写过的,和求解出栈顺序是一样的路子,直接套公式好了 Cn = Cn-1*(4*n-2)/(n+1),可以参考Catalan
class Solution {
public int numTrees(int n) {
long[] h = new long [n+1];
h[0] = h[1] = 1;
for (int i = 2; i <= n; i++) {
h[i] = h[i-1]*(4*i-2)/(i+1);
}
return (int)h[n];
}
}