-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1382-balance-a-binary-search-tree.js
More file actions
47 lines (40 loc) · 1.15 KB
/
1382-balance-a-binary-search-tree.js
File metadata and controls
47 lines (40 loc) · 1.15 KB
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
/**
* Balance a Binary Search Tree
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var balanceBST = function (rootNodeInput) {
const nodeValuesArray = [];
function traverseAndStore(currentVisitingNode) {
if (currentVisitingNode === null) {
return;
}
traverseAndStore(currentVisitingNode.left);
nodeValuesArray.push(currentVisitingNode.val);
traverseAndStore(currentVisitingNode.right);
}
traverseAndStore(rootNodeInput);
function constructBstFromSorted(startIndexForBuild, endIndexForBuild) {
if (startIndexForBuild > endIndexForBuild) {
return null;
}
const midIndexForBuild = Math.floor(
(startIndexForBuild + endIndexForBuild) / 2,
);
const currentTreeNode = new TreeNode(nodeValuesArray[midIndexForBuild]);
currentTreeNode.left = constructBstFromSorted(
startIndexForBuild,
midIndexForBuild - 1,
);
currentTreeNode.right = constructBstFromSorted(
midIndexForBuild + 1,
endIndexForBuild,
);
return currentTreeNode;
}
const finalBalancedTree = constructBstFromSorted(
0,
nodeValuesArray.length - 1,
);
return finalBalancedTree;
};