计算所有结构不同的二叉树数量的时间复杂度是多少?

时间:2010-03-29 02:23:14

标签: binary-tree complexity-theory memoization catalan

使用此处显示的方法:http://cslibrary.stanford.edu/110/BinaryTrees.html#java

12. countTrees() Solution (Java)
/**
 For the key values 1...numKeys, how many structurally unique
 binary search trees are possible that store those keys?

 Strategy: consider that each value could be the root.
 Recursively find the size of the left and right subtrees.
*/
public static int countTrees(int numKeys) {
  if (numKeys <=1) {
    return(1);
  }
  else {
    // there will be one value at the root, with whatever remains
    // on the left and right each forming their own subtrees.
    // Iterate through all the values that could be the root...
    int sum = 0;
    int left, right, root;

    for (root=1; root<=numKeys; root++) {
      left = countTrees(root-1);
      right = countTrees(numKeys - root);

      // number of possible trees with this root == left*right
      sum += left*right;
    }

    return(sum);
  }
} 

我感觉它可能是n(n-1)(n-2)... 1,即n!

如果使用记事本,复杂度是否为O(n)?

3 个答案:

答案 0 :(得分:2)

具有节点数n的完整二叉树的数量是第n个加泰罗尼亚数。加泰罗尼亚数字计算为

alt text

这是复杂性O(n)。

http://mathworld.wolfram.com/BinaryTree.html

http://en.wikipedia.org/wiki/Catalan_number#Applications_in_combinatorics

答案 1 :(得分:0)

很容易计算此算法用于countTrees的调用次数 给定的节点数。经过几次试运行后,我觉得它需要5 * 3 ^(n-2)次调用n> = 2,这比n!慢得多。这种说法的证据留给读者练习。 : - )

如你所知,记忆版需要O(n)个电话。

顺便提一下,n个节点的二叉树数量等于第n个Catalan number。 计算C n 的显而易见的方法在n中都是线性的,因此countTrees的备忘实现可能是最好的。

答案 2 :(得分:0)

不确定查找表中要记录的版本会有多少次点击(这肯定是超线性的,并且会有函数调用的开销),但是数学证明产生的结果是相同的作为第n个加泰罗尼亚语数字,可以快速制作线性时间表格方法:

    int C=1;
    for (int i=1; i<=n; i++)
    {
        C = (2*(2*(i-1)+1)*C/((i-1)+2));
    }
    return C;

请注意Memoization和Tabulation here

之间的区别