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

LeetCode —— Unique Binary Search Trees II

2013-09-03 09:26 316 查看
链接:http://leetcode.com/onlinejudge#question_95

原题:

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不变的性质,

重新构造二叉树。结果枚举失败。

去discussion里面看了一眼,晕倒,居然忘了二叉树这种题目是最适合用递归做的,呵呵。而且现在编译器都会优化,

直接返回一个vector,不再调用拷贝构造了。感谢yue liu大大告诉这些。

代码:

/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return constructTree(1, n);
}

private:
vector<TreeNode *> constructTree(int left, int right) {
vector<TreeNode *> trees;

if (left > right) {
trees.push_back(NULL);
return trees;
}

for (int i=left; i<=right; i++) {
auto leftSubs = constructTree(left, i-1);
auto rightSubs = constructTree(i+1, right);

for (int x=0; x<leftSubs.size(); x++) {
for (int y=0; y<rightSubs.size(); y++) {
TreeNode *root = new TreeNode(i);
root->left = leftSubs[x];
root->right = rightSubs[y];
trees.push_back(root);
}
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: