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.



public class Solution {
      
    public int numTrees(int n) {
        int result = 0;
        if(n==0||n==1){
            return 1;
        }else if(n==2){
            return 2;
        }
        // from 1 to n, compute root
        for(int i=1;i<=n;i++){
            result += numTrees(i-1)*numTrees(n-i);
        }
        return result;
    }
}


递归算法,利用两个性质:

1. 数是没有重复的, 只要确定一个数目那么构建树的方式数目是确定的,比如 [1,2,3], [1,2,4], [2,3,4]

构建树的方式都会是5种。

2. 只要确定一个根,那么以这个根所构建的二分搜索树

数目 = 左子树构建方式数*右子树构建方式数