题解 | #将升序数组转化为平衡二叉搜索树#
将升序数组转化为平衡二叉搜索树
https://www.nowcoder.com/practice/7e5b00f94b254da599a9472fe5ab283d
/* * function TreeNode(x) { * this.val = x; * this.left = null; * this.right = null; * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return TreeNode类 */ function sortedArrayToBST( nums ) { // write code here if (nums.length === 0) return null; function buildBST(left, right) { if (left > right) return null; const mid = Math.floor((left + right) / 2); const node = new TreeNode(nums[mid]); node.left = buildBST(left, mid - 1); node.right = buildBST(mid + 1, right); return node; } return buildBST(0, nums.length - 1); } module.exports = { sortedArrayToBST : sortedArrayToBST };