Skip to content

Commit

Permalink
Update and rename generateTrees.cpp to unique-binary-search-trees-ii.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Sep 7, 2016
1 parent d142de5 commit 23a2f51
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 41 deletions.
41 changes: 0 additions & 41 deletions C++/generateTrees.cpp

This file was deleted.

57 changes: 57 additions & 0 deletions C++/unique-binary-search-trees-ii.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Time: O(n * 4^n / n^(3/2)) ~= Catalan numbers
// Space: O(n)

/**
* 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) {
if (n == 0) {
return {};
}
return generateTreesHelper(1, n);
}

private:
vector<TreeNode *> generateTreesHelper(int start, int end) {
vector<TreeNode *> result;
if (start > end) {
result.emplace_back(nullptr);
return result;
}

for (int i = start; i <= end; ++i) {
vector<TreeNode *> leftSubTrees = generateTreesHelper(start, i - 1);
vector<TreeNode *> rightSubTrees = generateTreesHelper(i + 1, end);
for (const auto& left : leftSubTrees) {
for (const auto& right : rightSubTrees) {
TreeNode *root = new TreeNode(i);
root->left = clone(left);
root->right = clone(right);
result.emplace_back(root);
}
}

}
return result;
}

TreeNode *clone(TreeNode *root) {
TreeNode *newRoot = nullptr;

if (root) {
newRoot = new TreeNode(root->val);
newRoot->left = clone(root->left);
newRoot->right = clone(root->right);
}

return newRoot;
}
};

0 comments on commit 23a2f51

Please sign in to comment.