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.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
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:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as”{1,2,3,#,#,4,#,#,5}”.
典型的递归思路
/**
* Definition for binary tree
* 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) {
vector<TreeNode*> res;
if(n==0)
{res.push_back(NULL);return res;};
res=gener_tree(1,n);
return res;
}
vector<TreeNode*> gener_tree(int start,int end)
{
vector<TreeNode*> vec;
if(start>end)
{vec.push_back(NULL);return vec;}
for(int k=start;k<=end;++k){
vector<TreeNode*> left;
vector<TreeNode*> right;
left=gener_tree(start,k-1);
right=gener_tree(k+1,end);
for(int i=0;i<left.size();++i){
for(int j=0;j<right.size();++j)
{
TreeNode* root=new TreeNode(k);
root->left=left[i];
root->right=right[j];
vec.push_back(root);
}
}
}
return vec;
}
};