Skip to main content

1382.js

/** ------------------------------------------------------------------------------
*
* 1382. Balance a Binary Search Tree
* Topics: BST
* https://leetcode.com/problems/balance-a-binary-search-tree/description/
*
------------------------------------------------------------------------------ */
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/ var balanceBST = function (root) {
let arr = []
function dfs(root) {
if (root == null) return
dfs(root.left)
arr.push(root.val)
dfs(root.right)
}

dfs(root)

return sortedArrayToBST(arr)
}

var sortedArrayToBST = function (nums) {
const fn = (nums, left, right) => {
if (left >= right) return null
const mid = Math.floor((left + right) / 2)
return new TreeNode(nums[mid], fn(nums, left, mid), fn(nums, mid + 1, right))
}

return fn(nums, 0, nums.length)
}