题意:和Unique Binary Search Trees I一样,但是要返回不同的二分搜索树。
Given an integer 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.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3分析:
递归。假设以i为根,那么它的左子树是由(1,2,...,i-1)构成的不同的二分查找树的一种,右子树是由(i+1,i+2,...,n)构成的不同的二分查找树的一种。为每一种左右子树的组合都生成一棵新的树。要注意的是,当某个子树为空(即递归区间的下界大于上界)时,要返回的是NULL指针。所以要把一个NULL放进vector里返回。
代码:
/**
* 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*> generateTrees(int n) {
if(n==0) return vector<TreeNode*>();
return solve(1,n);
}
vector<TreeNode*> solve(int low,int high)
{
vector<TreeNode*> res;
if(low>high)
{
res.push_back(NULL);return res;
}
if(low==high)
{
TreeNode* temp=new TreeNode(low);
res.push_back(temp);return res;
}
for(int i=low;i<=high;i++)
{
vector<TreeNode*> left=solve(low,i-1);
vector<TreeNode*> right=solve(i+1,high);
for(int l=0;l<left.size();l++)
{
for(int r=0;r<right.size();r++)
{
TreeNode* root=new TreeNode(i);
root->left=left[l];root->right=right[r];
res.push_back(root);
}
}
}
return res;
}
};