LeetCode_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
confused what "{1,#,2,3}"
means?
> read more on how binary tree is serialized on OJ.
Show Tags
Have you met this question in a real interview?
Yes
No
二.解题技巧
这道题和Unique Binary Search Trees非常相似,仅仅是这道题可能无法使用动态规划降低计算的时间,由于每个节点的值是不一样的。不存在同样的子问题的情况,因此,计算复杂度无法下降。使用递归的方式进行的时候,时间复杂度为O(n^3),空间复杂度为O(n)。
三.实现代码
#include <iostream> #include <vector> #include <unordered_map> using std::vector; using std::unordered_map; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { private: unordered_map<int, vector<TreeNode*> > PreResult; vector<TreeNode*> generateTrees(int n, int base) { vector<TreeNode*> Result; if (n == 0) { TreeNode* TmpNode = NULL; Result.push_back(TmpNode); return Result; } if (n == 1) { TreeNode* TmpNode = new TreeNode(n + base); Result.push_back(TmpNode); return Result; } for (int HeadIndex = 1; HeadIndex <= n; HeadIndex++) { vector<TreeNode*> LeftChildVector = generateTrees(HeadIndex - 1, base); vector<TreeNode*> RightChildVector = generateTrees(n - HeadIndex, base + HeadIndex); const vector<TreeNode*>::size_type LEFTSIZE = LeftChildVector.size(); const vector<TreeNode*>::size_type RIGHTSIZE = RightChildVector.size(); for (vector<TreeNode*>::size_type IndexOfLeft = 0; IndexOfLeft < LEFTSIZE; IndexOfLeft++) { for (vector<TreeNode*>::size_type IndexOfRight = 0; IndexOfRight < RIGHTSIZE; IndexOfRight++) { TreeNode *TmpHeadNode = new TreeNode(base + HeadIndex); TmpHeadNode->left = LeftChildVector[IndexOfLeft]; TmpHeadNode->right = RightChildVector[IndexOfRight]; Result.push_back(TmpHeadNode); } } } return Result; } public: vector<TreeNode*> generateTrees(int n) { return generateTrees(n, 0); } };
四.体会
这道题也是一个和Unique Binary Search Trees类似的问题。解题思路也比較类似,仅仅是这个的返回是全部可能的二叉查找树,主要解答过程仅仅是略微改动下就可以。
版权全部,欢迎转载。转载请注明出处,谢谢![微笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)
![微笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)