-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy pathunique-binary-search-trees-ii.js
64 lines (53 loc) · 1.33 KB
/
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
*
* For example,
* Given n = 3, your program should return all 5 unique BST's shown below.
*
* 1 3 3 2 1
* \ / / / \ \
* 3 2 1 1 3 2
* / / \ \
* 2 1 2 3
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
import TreeNode from '../common/tree-node';
/**
* @param {number} n
* @return {TreeNode[]}
*/
const generateTrees = n => {
if (n <= 0) {
return [];
}
const helper = (lo, hi) => {
if (lo > hi) {
return [null];
}
if (lo === hi) {
return [new TreeNode(lo)];
}
const res = [];
for (let k = lo; k <= hi; k++) {
const leftBSTs = helper(lo, k - 1);
const rightBSTs = helper(k + 1, hi);
for (let i = 0; i < leftBSTs.length; i++) {
for (let j = 0; j < rightBSTs.length; j++) {
const treeNode = new TreeNode(k);
treeNode.left = leftBSTs[i];
treeNode.right = rightBSTs[j];
res.push(treeNode);
}
}
}
return res;
};
return helper(1, n);
};
export default generateTrees;