File tree 1 file changed +45
-0
lines changed
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * function TreeNode(val, left, right) {
4
+ * this.val = (val===undefined ? 0 : val)
5
+ * this.left = (left===undefined ? null : left)
6
+ * this.right = (right===undefined ? null : right)
7
+ * }
8
+ */
9
+ /**
10
+ * DFS | Recursion
11
+ * Time O(2^n) | Space O(2^n)
12
+ * https://leetcode.com/problems/all-possible-full-binary-trees/
13
+ * @param {number } n
14
+ * @return {TreeNode[] }
15
+ */
16
+ var allPossibleFBT = function ( n ) {
17
+
18
+ // even number of nodes can't make a full binary tree.
19
+ if ( ! ( n % 2 ) ) return [ ] ;
20
+
21
+ const dfs = ( n ) => {
22
+ if ( n === 1 ) return [ new TreeNode ( 0 ) ] ;
23
+
24
+ const allPossibleTrees = [ ] ;
25
+ for ( let i = 1 ; i < n ; i += 2 ) {
26
+
27
+ const leftNumOfNodes = i ;
28
+ const rightNumOfNodes = n - i - 1 ;
29
+
30
+ const leftTrees = dfs ( leftNumOfNodes ) ;
31
+ const rightTrees = dfs ( rightNumOfNodes ) ;
32
+
33
+ for ( let i = 0 ; i < leftTrees . length ; i ++ ) {
34
+ for ( let j = 0 ; j < rightTrees . length ; j ++ ) {
35
+ const root = new TreeNode ( 0 , leftTrees [ i ] , rightTrees [ j ] ) ;
36
+ allPossibleTrees . push ( root ) ;
37
+ }
38
+ }
39
+ }
40
+
41
+ return allPossibleTrees ;
42
+ }
43
+
44
+ return dfs ( n ) ;
45
+ } ;
You can’t perform that action at this time.
0 commit comments