题解 | 将升序数组转化为平衡二叉搜索树

将升序数组转化为平衡二叉搜索树

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) 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
};

全部评论

相关推荐

点赞 评论 收藏
分享
05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
找工作时遇到的神仙HR
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 12:10
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务