【leetcode】Unique Binary Search Trees II

Unique Binary Search Trees II

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
 
 
从1-n中选取一个元素i,i左边的元素都在左子树上,i右边的元素都在右子树上
 
 /**
* 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 *>result=build(,n);
return result;
} vector<TreeNode *> build(int l,int r)
{ if(l>r)
{
vector<TreeNode *> root();
root[]=NULL;
return root;
} vector<TreeNode *> result; for(int i=l;i<=r;i++)
{
vector<TreeNode *> left=build(l,i-);
vector<TreeNode *> right=build(i+,r);
for(int j=;j<left.size();j++)
{
for(int k=;k<right.size();k++)
{
TreeNode *root=new TreeNode(i);
root->left=left[j];
root->right=right[k];
result.push_back(root); }
}
} return result;
}
};
上一篇:PHP和javascript中url编码解码详解


下一篇:Hive 商品案例