-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0894-all-possible-full-binary-trees.js
More file actions
44 lines (39 loc) · 1.15 KB
/
0894-all-possible-full-binary-trees.js
File metadata and controls
44 lines (39 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* All Possible Full Binary Trees
* Time Complexity: O(N * C_N_prime)
* Space Complexity: O(N * C_N_prime)
*/
var allPossibleFBT = function (n) {
const memoizationCache = new Map();
function constructFullBinaryTrees(totalNodes) {
if (totalNodes % 2 === 0) {
return [];
}
if (totalNodes === 1) {
return [new TreeNode(0)];
}
if (memoizationCache.has(totalNodes)) {
return memoizationCache.get(totalNodes);
}
const resultingTrees = [];
for (
let nodesForLeft = 1;
nodesForLeft < totalNodes - 1;
nodesForLeft += 2
) {
const nodesForRight = totalNodes - 1 - nodesForLeft;
const leftTreeOptions = constructFullBinaryTrees(nodesForLeft);
const rightTreeOptions = constructFullBinaryTrees(nodesForRight);
for (const currentLeftTree of leftTreeOptions) {
for (const currentRightTree of rightTreeOptions) {
resultingTrees.push(
new TreeNode(0, currentLeftTree, currentRightTree),
);
}
}
}
memoizationCache.set(totalNodes, resultingTrees);
return resultingTrees;
}
return constructFullBinaryTrees(n);
};