What would be the time complexity of counting the number of all structurally different binary trees?

我的梦境 提交于 2019-12-05 13:02:04
Robert Harvey

The number of full binary trees with number of nodes n is the nth Catalan number. Catalan Numbers are calculated as

which is complexity O(n).

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

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

It's easy enough to count the number of calls to countTrees this algorithm uses for a given node count. After a few trial runs, it looks to me like it requires 5*3^(n-2) calls for n >= 2, which grows much more slowly than n!. The proof of this assertion is left as an exercise for the reader. :-)

A memoized version required O(n) calls, as you suggested.

Incidentally, the number of binary trees with n nodes equals the n-th Catalan number. The obvious approaches to calculating Cn all seem to be linear in n, so a memoized implementation of countTrees is probably the best one can do.

Not sure of how many hits to the look-up table is the memoized version going to make (which is definitely super-linear and will have the overheads of function calling) but with the mathematical proof yielding the result to be the same as nth Catalan number, one can quickly cook up a linear-time tabular method:

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

Note the difference between Memoization and Tabulation here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!