首页 > 代码库 > Unique Binary Search Trees

Unique Binary Search Trees

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

 C++代码实现:

#include<iostream>using namespace std;class Solution {public:    int numTrees(int n) {        if(n<0)            return 0;        if(n==1||n==0)            return 1;        int result=1;        int i;        for(i=2;i<=n;++i)            result=(4*i-2)*result/(i+1);        return result;    }};int main(){    Solution s;    cout<<s.numTrees(4)<<endl;}

类似递推公式可以参考:http://blog.csdn.net/u011466175/article/details/38710947

 

Unique Binary Search Trees