您的位置:首页 > 产品设计 > UI/UE

【leetcode】Unique Binary Search Trees II

2015-01-11 14:28 417 查看

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(1,n);
return result;
}

vector<TreeNode *> build(int l,int r)
{

if(l>r)
{
vector<TreeNode *> root(1);
root[0]=NULL;
return root;
}

vector<TreeNode *> result;

for(int i=l;i<=r;i++)
{
vector<TreeNode *> left=build(l,i-1);
vector<TreeNode *> right=build(i+1,r);
for(int j=0;j<left.size();j++)
{
for(int k=0;k<right.size();k++)
{
TreeNode *root=new TreeNode(i);
root->left=left[j];
root->right=right[k];
result.push_back(root);

}
}
}

return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: