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……n不变的性质,
重新构造二叉树。结果枚举失败。
去discussion里面看了一眼,晕倒,居然忘了二叉树这种题目是最适合用递归做的,呵呵。而且现在编译器都会优化,
直接返回一个vector,不再调用拷贝构造了。感谢yue liu大大告诉这些。
代码:
原题:
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); } } } } };
相关文章推荐
- LeetCode - Unique Binary Search Trees II
- 【LeetCode】Unique Binary Search Trees II
- 95. Unique Binary Search Trees II LeetCode
- leetcode — unique-binary-search-trees-ii
- leetcode Unique Binary Search Trees II
- [LeetCode] Unique Binary Search Trees II
- [Leetcode] Unique binary search trees ii 唯一二叉搜索树
- LeetCode 95. Unique Binary Search Trees II
- (复习)[LeetCode]Unique Binary Search Trees II
- Leetcode 95 Unique Binary Search Trees II
- LeetCode||95. Unique Binary Search Trees II
- [LeetCode] 95. Unique Binary Search Trees II
- LeetCode Unique Binary Search Trees II
- leetcode-Unique Binary Search Trees II
- leetcode先刷_Unique Binary Search Trees II
- LeetCode-Unique Binary Search Trees II
- [leetcode] 95.Unique Binary Search Trees II
- Leetcode 95. Unique Binary Search Trees II
- [Leetcode] 95. Unique Binary Search Trees II 解题报告
- Unique Binary Search Trees II -- LeetCode