Skip to content

Commit 7238840

Browse files
authored
Create 1382-balance-a-binary-search-tree.js
1 parent 3daa3fc commit 7238840

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

1382-balance-a-binary-search-tree.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @return {TreeNode}
12+
*/
13+
const balanceBST = function(root) {
14+
const arr = []
15+
inOrder(root, arr)
16+
return constructBST(arr, 0, arr.length - 1)
17+
};
18+
19+
function inOrder(node, arr) {
20+
if(node == null) return
21+
inOrder(node.left, arr)
22+
arr.push(node.val)
23+
inOrder(node.right, arr)
24+
}
25+
26+
function constructBST(arr, start, end) {
27+
if(start > end) return null
28+
const mid = start + ((end - start) >> 1)
29+
const node = new TreeNode(arr[mid])
30+
node.left = constructBST(arr, start, mid - 1)
31+
node.right = constructBST(arr, mid + 1, end)
32+
return node
33+
}

0 commit comments

Comments
 (0)