Q7: 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
解决原理1:
遍历+递归
二叉查找树的根节点可以是1~n中的任何一个数i
根为i的二叉树数量=左子树数量*右子树数量
左子树的根节点取值范围为1~i,右子树的根节点取值范围为i+1~n,i+1~n组成的二叉查找树的数量又与1~n-i的相同
代码1:
1 class Solution { 2 int sum; 3 public: 4 int numTrees(int n) { 5 if(n == 0) return 0; 6 if(n == 1) return 1; 7 for(int i = 1; i <= n; i++){ 8 int l = numTrees(i-1); 9 int r = numTrees(n-i); 10 sum = sum + (l==0?1:l) * (r==0?1:r); 11 } 12 return sum; 13 } 14 };
但是,此方法超时