Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
解题: 有一个很简单的结论,就是节点数为n的二叉树共有h(n)种形态,其中h(n)是卡特兰数,h(n) = C(2*n,n)/(n+1);
所以只要按这个公式计算就是可以了。注意变量要取long long int型,否则会溢出。
代码:
1 class Solution { 2 public: 3 int numTrees(int n) { 4 long long int n_factorial = 1; 5 long long int tn_fac = 1; 6 for(int i = 1;i <= n;i ++) 7 n_factorial *= i; 8 for(int i = n+1;i <= 2*n;i ++) 9 tn_fac *= i; 10 return (tn_fac)/(n_factorial*(n+1)); 11 } 12 };
题外话:为什么节点数为n的二叉树有h(n)种形态呢?
当n=0时,h(0)=1;
当n=1时,h(1)=1;
当n>=2时,分别考虑树的左子树和右子树,它们的节点数分别可以取(0,n-1),(1,n-2),....,(n-2,1),(n-1,0),所以h(n)=h(0)*h(n-1)+h(1)*h(n-2)+...+h(n-1,0)h(0),这个递推式解得到的数就是卡特兰数。