Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit a5bf072

Browse files
committedMar 22, 2025
Add solution #894
1 parent a4257c4 commit a5bf072

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,7 @@
704704
891|[Sum of Subsequence Widths](./0891-sum-of-subsequence-widths.js)|Hard|
705705
892|[Surface Area of 3D Shapes](./0892-surface-area-of-3d-shapes.js)|Easy|
706706
893|[Groups of Special-Equivalent Strings](./0893-groups-of-special-equivalent-strings.js)|Medium|
707+
894|[All Possible Full Binary Trees](./0894-all-possible-full-binary-trees.js)|Medium|
707708
901|[Online Stock Span](./0901-online-stock-span.js)|Medium|
708709
905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy|
709710
909|[Snakes and Ladders](./0909-snakes-and-ladders.js)|Medium|
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* 894. All Possible Full Binary Trees
3+
* https://leetcode.com/problems/all-possible-full-binary-trees/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer n, return a list of all possible full binary trees with n nodes. Each node
7+
* of each tree in the answer must have Node.val == 0.
8+
*
9+
* Each element of the answer is the root node of one possible tree. You may return the final
10+
* list of trees in any order.
11+
*
12+
* A full binary tree is a binary tree where each node has exactly 0 or 2 children.
13+
*/
14+
15+
/**
16+
* Definition for a binary tree node.
17+
* function TreeNode(val, left, right) {
18+
* this.val = (val===undefined ? 0 : val)
19+
* this.left = (left===undefined ? null : left)
20+
* this.right = (right===undefined ? null : right)
21+
* }
22+
*/
23+
/**
24+
* @param {number} n
25+
* @return {TreeNode[]}
26+
*/
27+
var allPossibleFBT = function(n) {
28+
const memo = new Map();
29+
return generateTrees(n);
30+
31+
function generateTrees(nodes) {
32+
if (nodes % 2 === 0) return [];
33+
if (nodes === 1) return [new TreeNode(0)];
34+
if (memo.has(nodes)) return memo.get(nodes);
35+
36+
const result = [];
37+
for (let leftNodes = 1; leftNodes < nodes - 1; leftNodes += 2) {
38+
const rightNodes = nodes - 1 - leftNodes;
39+
const leftTrees = generateTrees(leftNodes);
40+
const rightTrees = generateTrees(rightNodes);
41+
42+
for (const left of leftTrees) {
43+
for (const right of rightTrees) {
44+
result.push(new TreeNode(0, left, right));
45+
}
46+
}
47+
}
48+
49+
memo.set(nodes, result);
50+
return result;
51+
}
52+
};

0 commit comments

Comments
 (0)
Please sign in to comment.