-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0894-all-possible-full-binary-trees.js
45 lines (37 loc) · 1.2 KB
/
0894-all-possible-full-binary-trees.js
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
45
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* DFS | Recursion
* Time O(2^n) | Space O(2^n)
* https://leetcode.com/problems/all-possible-full-binary-trees/
* @param {number} n
* @return {TreeNode[]}
*/
var allPossibleFBT = function(n) {
// even number of nodes can't make a full binary tree.
if(!(n % 2)) return [];
const dfs = (n) => {
if(n === 1) return [new TreeNode(0)];
const allPossibleTrees = [];
for(let i = 1; i < n; i += 2) {
const leftNumOfNodes = i;
const rightNumOfNodes = n - i - 1;
const leftTrees = dfs(leftNumOfNodes);
const rightTrees = dfs(rightNumOfNodes);
for(let i = 0; i < leftTrees.length; i++) {
for(let j = 0; j < rightTrees.length; j++) {
const root = new TreeNode(0, leftTrees[i], rightTrees[j]);
allPossibleTrees.push(root);
}
}
}
return allPossibleTrees;
}
return dfs(n);
};