-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathsolution1.js
More file actions
38 lines (36 loc) · 758 Bytes
/
Copy pathsolution1.js
File metadata and controls
38 lines (36 loc) · 758 Bytes
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
/**
*
* https://leetcode-cn.com/problems/balance-a-binary-search-tree/
*
* 5179. 将二叉搜索树变平衡
*
* Medium
*
* 184ms 100.00%
* 55.7mb 100.00%
*
*/
const balanceBST = root => {
const nodes = [];
help(root, nodes);
return generateBalanceBST(nodes);
}
function help(root, nodes) {
if (!root) {
return;
}
help(root.left, nodes);
nodes.push(root.val);
help(root.right, nodes);
}
function generateBalanceBST(nodes) {
if (!nodes.length) {
return null;
}
const midIndex = Math.floor(nodes.length / 2);
const mid = nodes[midIndex];
const tree = new TreeNode(mid);
tree.left = generateBalanceBST(nodes.slice(0, midIndex));
tree.right = generateBalanceBST(nodes.slice(midIndex + 1));
return tree;
}