Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
all-possible-full-binary-trees.cpp 1.18 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2018-08-26 23:47 +08:00 . Create all-possible-full-binary-trees.cpp
// Time: O(n * 4^n / n^(3/2)) ~= sum of Catalan numbers from 1 .. N
// Space: O(n * 4^n / n^(3/2)) ~= sum of Catalan numbers from 1 .. 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*> allPossibleFBT(int N) {
if (!memo_.count(N)) {
vector<TreeNode*> result;
if (N == 1) {
result.emplace_back(new TreeNode(0));
} else if (N % 2 == 1) {
for (int i = 0; i < N; ++i) {
for (const auto& left: allPossibleFBT(i)) {
for (const auto& right: allPossibleFBT(N - 1 - i)) {
auto node = new TreeNode(0);
node->left = left;
node->right = right;
result.emplace_back(node);
}
}
}
}
memo_[N] = move(result);
}
return memo_[N];
}
private:
unordered_map<int, vector<TreeNode*>> memo_;
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助