题目
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.
confused what “{1,#,2,3}” means? > read more on how binary tree is serialized on OJ.
OJ’s Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.
Here’s an example:
The above binary tree is serialized as “{1,2,3,#,#,4,#,#,5}”.
分析
给定整数n,求输入元素为 [1,n] 时,所构成的全部二叉查找树;
我们都知道二叉查找树的特点,左子树节点值小于根节点,右子树节点值大于根节点。
对于输入
[1,n]
,每个值
i
都可以作为根节点,小于
所以,此题的解决办法为二叉树常用递归。
AC代码
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
if (n <= 0)
return vector<TreeNode *>(1 , NULL);
//对值为 [1 , n]的每个元素都可做二叉查找树的根节点
return generateTrees(1, n);
}
//构造根节点[lhs , rhs]的所有二叉查找树
vector<TreeNode *> generateTrees(int lhs, int rhs)
{
if (lhs > rhs)
{
return vector<TreeNode *>(1 , NULL);
}
//存储每个查找树的根节点
vector<TreeNode *> ret;
for (int r = lhs; r <= rhs; r++)
{
//[lhs~r-1]间节点作为左子树,[r+1~rhs]间节点作为右子树
vector<TreeNode *> lefts = generateTrees(lhs, r - 1);
vector<TreeNode *> rights = generateTrees(r + 1, rhs);
//链接符合要求的左右子树
int lsize = lefts.size();
int rsize = rights.size();
for (int i = 0; i < lsize; ++i)
{
for (int j = 0; j < rsize; ++j)
{
//当前节点作为根节点
TreeNode *root = new TreeNode(r);
root->left = lefts[i];
root->right = rights[j];
ret.push_back(root);
}//for
}//for
}//for
return ret;
}
};