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.youkuaiyun.com/jiadebin890724/article/details/23305915
/*
*/
#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];
}
};
1045



被折叠的 条评论
为什么被折叠?



