96. Unique Binary Search Trees
- Total Accepted: 116783
- Total Submissions: 288808
- Difficulty: Medium
- Contributor: LeetCode
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
Subscribe to see which companies asked this question.
Show Similar Problems
思路:
假设二叉树的总数为f(n),考虑f(n)和f(n-1)的关系,因为n为最大数,所以它可以成为f(n-1)的最右的一片叶子,也可以作为根。另外,如果把n插入f(n-1)的二叉树中间,若在n的上面有i个元素,则有f(i)种可能,而在下
面则有(n-1-i)个元素,有f(n-1-i)种可能。故f(n) = f(n-1) * 2 + f(i) * f(n-1-i) + .....,其中i从1到n-2。
代码:
class Solution {
public:
int numTrees(int n) {
if(n == 1) return 1;
else if(n == 2) return 2;
else{
int k = 0;
for(int i = 1; i < n - 1; i ++){
k = k + numTrees(i) * numTrees(n - 1 - i);
}
return numTrees(n - 1) * 2 + k;
}
}
};