假設給定n個節點,節點值爲1,2,3...,n,求由這些結點可以構成多少棵不同的二叉查找樹。
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
思路:遞歸,由於是二叉查找樹,先選擇任一結點根結點,假設爲結點i,則[1,i-1]範圍的結點爲結點i的左子樹結點,[i+1,n]範圍的結點爲結點i的右子樹結點,則以結點i爲根結點的BST個數爲左,右子樹可構成BST個數的乘積,基於這個思路,可以寫出以下遞歸程序。
class Solution {
public:
int numTrees(int n)
{
return numTrees(1,n);
}
int numTrees(int start, int end)
{
if (start >= end)
return 1;
int totalNum = 0;
for (int i=start; i<=end; ++i)
totalNum += numTrees(start,i-1)*numTrees(i+1,end);
return totalNum;
}
};