|
| 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