LeetCode_Unique Binary Search Trees II
I. Question Unique Binary Search Trees IITotal Accepted: 32757 Total Submissions: 117071My Submissions
Given n, generate all structurally unique BST's (binary search trees) that store values 1... n.
For example,
Given n = 3, your program shocould 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
Discuss
Ii. problem-solving skillsThis question is very similar to the Unique Binary Search Trees, but it may not be possible to use dynamic planning to reduce the computing time, because the values of each node are different and there are no identical subproblems, therefore, the computing complexity cannot be reduced. In recursive mode, the time complexity is O (n ^ 3) and the space complexity is O (n ).
Iii. Implementation Code
#include
#include
#include
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
> PreResult; vector
generateTrees(int n, int base) { vector
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
LeftChildVector = generateTrees(HeadIndex - 1, base); vector
RightChildVector = generateTrees(n - HeadIndex, base + HeadIndex); const vector
::size_type LEFTSIZE = LeftChildVector.size(); const vector
::size_type RIGHTSIZE = RightChildVector.size(); for (vector
::size_type IndexOfLeft = 0; IndexOfLeft < LEFTSIZE; IndexOfLeft++) { for (vector
::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
generateTrees(int n) { return generateTrees(n, 0); }};
Iv. ExperienceThis is also a problem similar to the Unique Binary Search Trees. The solution is similar, but the returned result is all possible Binary Search Trees. The main solution process is just a slight modification.