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
知识点补充:
二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
思路分析:
参考文章:http://blog.csdn.net/jiadebin890724/article/details/23305915
本题其实关键是递推过程的分析,n个点中每个点都可以作为root,当 i 作为root时,小于 i 的点都只能放在其左子树中,大于 i 的点只能放在右子树中,此时只需求出左、右子树各有多少种,二者相乘即为以 i 作为root时BST的总数。
开始时,我尝试用递归实现,但是超时了,可见系统对运行时间有要求。因为递归过程中存在大量的重复计算,从n一层层往下递归,故考虑类似于动态规划的思想,让底层的计算结果能够被重复利用,故用一个数组存储中间计算结果(即 1~n-1 对应的BST数目),这样只需双层循环即可,代码如下:
/*
*/
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution_096_UniqueBinarySearchTree
{
public:
int numTrees(int n)
{
vector<int> num;
num.push_back(1);
for (int i = 1; i <= n; i++)
{
num.push_back(0);
if (i < 3)
{
num[i] = i;
}
else
{
for (int j = 1; j <= i; j++)
{
num[i] += num[j - 1] * num[i - j]; //此时节点总数为i - 1, 因为有一个root节点
}
}
}
return num[n];
}
};