-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0095-unique-binary-search-trees-ii.js
47 lines (40 loc) · 1.18 KB
/
0095-unique-binary-search-trees-ii.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
46
47
/**
* 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)
* }
*/
/**
* Recursion
* Time O(4^n) | Space O(n)
* https://leetcode.com/problems/unique-binary-search-trees-ii/
* @param {number} n
* @return {TreeNode[]}
*/
var generateTrees = function(n) {
const dfs = (start, end) => {
const result = [];
if(start === end) {
result.push(new TreeNode(start));
return result;
};
if(start > end) {
result.push(null);
return result;
};
for(let i = start; i < end + 1; i++) {
const leftSubTrees = dfs(start, i - 1);
const rightSubTrees = dfs(i + 1 , end);
leftSubTrees.forEach((leftSubTree) => {
rightSubTrees.forEach((rightSubTree) => {
const root = new TreeNode(i, leftSubTree, rightSubTree);
result.push(root);
});
});
}
return result;
}
return dfs(1, n);
};