tree - 唯一二叉搜索树

标签 tree catalan

关闭。这个问题是off-topic .它目前不接受答案。












想改善这个问题吗? Update the question所以它是 on-topic对于堆栈溢出。

9年前关闭。




Improve this question




给定一组整数,找出可以从中构造出多少唯一的二叉搜索树???

根据我的说法,答案取决于整数集的大小。

我不确定答案..我说得对吗???

最佳答案

这可以通过使用动态规划来解决。

numTrees(i+1)=append the last node to the rightmost leaf of bst(i)[numTrees(i)] +
              append the last node as the root of bst(i)[numTrees(i)] +
              insert the last node as non-leaf node sum(k=1...i)(bst(k-1)*bst(i-k)

所以它是 o(n^2) 解决方案。
public int numTrees(int n) {
    if(n == 0 || n == 1 || n == 2)
        return n;
    int bst[] = new int[n+1];
    bst[0] = 1;
    bst[1] = 1;
    bst[2] = 2;
    for (int i=3; i<=n; i++) {
        for (int j=1; j<i-1; j++) {
            bst[i] += bst[j]*bst[i-1-j];
        }
        bst[i] += 2*bst[i-1];
    }
    return bst[n];
}

关于tree - 唯一二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6190942/

相关文章:

algorithm - 生成括号问题的闭包数法

c - 我的 C 代码加泰罗尼亚数字不起作用(使用递归公式)

php - 如何在 php 中构建具有 id、parent_id 和深度变量的树

Javascript Infovis 更改单个节点颜色

algorithm - 缓存感知树的实现

java - 关于生成树的递归方法的问题

c++ - 长号。分配

javascript - TypeScript 中的类型级 Catalan 函数

algorithm - 正确排列括号的方法数

c++ - 嵌套开关替代