/* * 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) return null; if (nums.length === 1) return new TreeNode(nums[0]); // find the root, in middle const rootIndex = Math.floor(nums.length / 2); const root = new TreeNode(nums[rootIndex]); // find the next root in the subtree if (rootIndex - 1 >= 0) root.left = sortedArrayToBST(nums.slice(0, rootIndex)); if (rootIndex + 1 <= nums.length - 1) root.right = sortedArrayToBST(nums.slice(rootIndex+1)); return root; } module.exports = { sortedArrayToBST : sortedArrayToBST };