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}"
.
class Solution { public: vector<TreeNode *> generateTrees(int n) { // Note: The Solution object is instantiated only once and is reused by each test case. if(n==0){ vector<TreeNode*> aaa; aaa.push_back(NULL); return aaa; } vector<vector<vector<TreeNode*> > > vec; vector<vector<TreeNode*> >one; for(int i=0;i<=n;i++){ one.resize(n-i+1); vec.push_back(one); } for(int j=0;j<n;j++){ vec[j][0].push_back(NULL); vec[j][1].push_back(new TreeNode(j+1)); } vec[n][0].push_back(NULL); for(int j=2;j<=n;j++){ for(int i=0;i<=n-j;i++){ for(int k=0;k<j;k++){ for(int l=0;l<vec[i][k].size();l++){ for(int r=0;r<vec[i+k+1][j-k-1].size();r++){ TreeNode* root=new TreeNode(i+k+1); root->left=vec[i][k][l]; root->right=vec[i+k+1][j-k-1][r]; vec[i][j].push_back(root); } } } } } return vec[0][n]; } };