Description:
Given n, generate all structurally unique BST’s (binary search trees) that store values 1…n.
For example, Given n = 3, your program should return all 5 unique BST’s shown below.
分析:找到一个根节点,剩余的数分别划分为左右子树。
代码:
#include <iostream>
#include <vector>
#define Elementype int
using namespace std;
typedef struct TreeNode //树结点
{
Elementype val;
TreeNode *left;
TreeNode *right;
TreeNode(Elementype x) : val(x), left(nullptr), right(nullptr) {}
} *Tree;
vector<Tree> BuildTree(int start, int end)
{
vector<Tree> tree;
if (start > end)
{
tree.push_back(nullptr);
}
for (int k = start; k <= end; k++)
{
vector<Tree>leftTree = BuildTree(start, k - 1);
vector<Tree>rightTree = BuildTree(k + 1, end);
for (auto i : leftTree)
{
for (auto j : rightTree)
{
Tree root = new TreeNode(k);
root->left = i;
root->right = j;
tree.push_back(root);
}
}
}
return tree;
}
int main()
{
int n;
cout << "请输入整数n: ";
cin >> n;
cout << "输出根节点: " << endl;
vector<Tree> result = BuildTree(1,n);
for (auto it = result.begin(); it != result.end(); it++)
cout << (*it)->val << " ";
cout << endl;
system("pause");
return 0;
}
测试: