【问题标题】:unique binary search trees [closed]唯一的二叉搜索树
【发布时间】:2011-05-31 16:58:54
【问题描述】:

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

根据我的说法,答案取决于整数集的大小。如果集合整数的大小是 n..那么可以用它制作“n”个唯一的二叉搜索树..

我不确定答案..我是对的吗???

【问题讨论】:

标签: tree catalan


【解决方案1】:

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

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];
}

【讨论】:

    【解决方案2】:

    数字是 C_n,其中 C_n 是第 n 个Catalan Number。该值可以递归地定义,方法是选择n个节点中的任何一个作为根,然后采用所有可能的方式组织根的左右子树,从而导致以下递归关系:

    C_n = sum_{i = 0}^{n - 1} C_i * C_{n - 1 - i},

    其中 C_0 = 1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      相关资源
      最近更新 更多