题解 | #将升序数组转化为平衡二叉搜索树#
将升序数组转化为平衡二叉搜索树
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 ) { if(nums.length === 0) { return null } function tree(nums, left, right) { if(left > right) return null // const mid = Math.floor((right - left) / 2); // 向低位取, 也是正确的, 只是案例给的是向高位取的结果 const mid = Math.ceil((left + right) / 2); // 向高位取 const root = new TreeNode(nums[mid]) root.left = tree(nums, left, mid - 1) root.right = tree(nums, mid + 1, right) return root; } return tree(nums, 0, nums.length - 1) // write code here } module.exports = { sortedArrayToBST : sortedArrayToBST };