-
Notifications
You must be signed in to change notification settings - Fork 42
/
solution.js
75 lines (66 loc) · 2.17 KB
/
solution.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
65
66
67
68
69
70
71
72
73
74
75
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {number} n
* @return {TreeNode[]}
*/
// 分治思想
var generateTrees = function (n) {
const arr = Array.apply(null, {
length: n,
}).map((item, index) => index + 1);
function divideConquer (arr, startIndex, endIndex) {
if (startIndex > endIndex) {
return [];
}
const rst = [];
for (let i = startIndex; i <= endIndex; i++) {
// arr[i] 作为根节点的值
if (startIndex === endIndex) {
rst.push(new TreeNode(arr[i]));
continue;
}
// 划分左右
const leftNodes = divideConquer(arr, startIndex, i - 1);
const rightNodes = divideConquer(arr, i + 1, endIndex);
const leftLength = leftNodes.length;
const rightLength = rightNodes.length;
// 左右都有节点 有 leftLength*rightLength种情况
if (leftLength && rightLength) {
for (let j = 0; j < leftNodes.length; j++) {
for (let k = 0; k < rightNodes.length; k++) {
const node = new TreeNode(arr[i]);
node.left = leftNodes[j];
node.right = rightNodes[k];
rst.push(node);
}
}
continue;
}
// 最多只有一侧有子节点
if (!leftLength) {
for (let j = 0; j < rightNodes.length; j++) {
const node = new TreeNode(arr[i]);
node.right = rightNodes[j];
rst.push(node);
}
continue;
}
if (!rightLength) {
for (let j = 0; j < leftNodes.length; j++) {
const node = new TreeNode(arr[i]);
node.left = leftNodes[j];
rst.push(node);
}
continue;
}
}
return rst;
}
return divideConquer(arr, 0, n - 1);
};