96 不同的二叉搜索树
题目地址【96】
题目描述:
给定一个整数 n,求以 1 … n 为节点组成的二叉搜索树有多少种?
示例
输入:3
输出:5
解释:给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
思路
此题是一道动态规划问题:问题可以理解为:
给定一个有序序列 1 … n,为了根据序列构建一棵二叉搜索树。我们可以遍历每个数字 i,将该数字作为树根,1 … (i-1) 序列将成为左子树,(i+1) … n 序列将成为右子树。于是,我们可以递归地从子序列构建子树。
在上述方法中,由于根各自不同,每棵二叉树都保证是独特的。
可见,问题可以分解成规模较小的子问题。因此,我们可以存储并复用子问题的解,而不是递归的(也重复的)解决这些子问题,这就是动态规划法。
代码
class Solution {
public:
int numTrees(int n) {
vector<int>x(n+1);
x[0] = 1;
x[1] = 1;
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= i; j++) {
x[i] += x[j - 1] * x[i - j];
}
}
return x[n];
}
};
反思
这里用到的一个很重要的性质是二叉搜索树大小关系,对于任何二叉搜索树,左小右大的关系是确定的,所以,左右两边可以拆分成更小的一样的子问题
更简便的做法
这种是利用卡特兰数,吾等凡夫俗子就想不出来了
95 不同的二叉搜索树Ⅱ
题目描述
给定一个整数 n,生成所有由 1 … n 为节点所组成的二叉搜索树。
示例
思路
几乎和上次一样,但是这个使用了纯递归的方法
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode*>generate_trees(int start, int end) {
vector<TreeNode*>all_trees;
if (start > end) {
all_trees.push_back(NULL);
return all_trees;
}
for (int i = start; i <= end; i++) {
vector<TreeNode*>left_trees = generate_trees(start, i - 1);
vector<TreeNode*>right_trees = generate_trees(i + 1, end);
for (int m = 0; m < left_trees.size(); m++) {
for (int j = 0; j < right_trees.size(); j++) {
TreeNode* node = new TreeNode(i);
node->left = left_trees[m];
node->right = right_trees[j];
all_trees.push_back(node);
}
}
}
return all_trees;
}
vector<TreeNode*> generateTrees(int n) {
if (n <= 0) {
vector<TreeNode*>allTree;
return allTree;
}
else return generate_trees(1, n);
}
};