Skip to content

Commit 9823847

Browse files
committed
Add solution #1382
1 parent ec269a0 commit 9823847

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,266 LeetCode solutions in JavaScript
1+
# 1,267 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1053,6 +1053,7 @@
10531053
1379|[Find a Corresponding Node of a Binary Tree in a Clone of That Tree](./solutions/1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.js)|Easy|
10541054
1380|[Lucky Numbers in a Matrix](./solutions/1380-lucky-numbers-in-a-matrix.js)|Easy|
10551055
1381|[Design a Stack With Increment Operation](./solutions/1381-design-a-stack-with-increment-operation.js)|Medium|
1056+
1382|[Balance a Binary Search Tree](./solutions/1382-balance-a-binary-search-tree.js)|Medium|
10561057
1389|[Create Target Array in the Given Order](./solutions/1389-create-target-array-in-the-given-order.js)|Easy|
10571058
1400|[Construct K Palindrome Strings](./solutions/1400-construct-k-palindrome-strings.js)|Medium|
10581059
1402|[Reducing Dishes](./solutions/1402-reducing-dishes.js)|Hard|
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 1382. Balance a Binary Search Tree
3+
* https://leetcode.com/problems/balance-a-binary-search-tree/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary search tree, return a balanced binary search tree with the same
7+
* node values. If there is more than one answer, return any of them.
8+
*
9+
* A binary search tree is balanced if the depth of the two subtrees of every node never differs
10+
* by more than 1.
11+
*/
12+
13+
/**
14+
* Definition for a binary tree node.
15+
* function TreeNode(val, left, right) {
16+
* this.val = (val===undefined ? 0 : val)
17+
* this.left = (left===undefined ? null : left)
18+
* this.right = (right===undefined ? null : right)
19+
* }
20+
*/
21+
/**
22+
* @param {TreeNode} root
23+
* @return {TreeNode}
24+
*/
25+
var balanceBST = function(root) {
26+
const nodes = [];
27+
collectInOrder(root);
28+
return buildBalancedTree(0, nodes.length - 1);
29+
30+
function collectInOrder(node) {
31+
if (!node) return;
32+
collectInOrder(node.left);
33+
nodes.push(node.val);
34+
collectInOrder(node.right);
35+
}
36+
37+
function buildBalancedTree(start, end) {
38+
if (start > end) return null;
39+
const mid = Math.floor((start + end) / 2);
40+
const node = new TreeNode(nodes[mid]);
41+
node.left = buildBalancedTree(start, mid - 1);
42+
node.right = buildBalancedTree(mid + 1, end);
43+
return node;
44+
}
45+
};

0 commit comments

Comments
 (0)