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

经典中的经典Unique Binary Search Trees II

2015-07-29 20:37 344 查看


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

 迄今为止看到的最为经典的算法,分数超过14000的好评

最经典的解法:


/**
* 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) {
return helper(1, n);
}
vector<TreeNode*> helper(int s, int e){
if(s>e){
return vector<TreeNode*>(1, NULL);
}

vector<TreeNode *> res;
for(int i=s; i<=e; i++){
vector<TreeNode *> left=helper(s, i-1);
vector<TreeNode *> right=helper(i+1, e);
for(int j=0; j<left.size(); j++){
for(int k=0; k<right.size(); k++){
TreeNode * p=new TreeNode(i);
p->left=left[j];
p->right=right[k];
res.push_back(p);
}
}
}
return res;
}
};
来自leetcode:https://leetcode.com/discuss/26330/30-ms-c-solution
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息