Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

108. 将有序数组转换为二叉搜索树 #79

Open
Labels
@Geekhyt

Description

@Geekhyt

原题链接

递归

  1. 二叉搜索树的中序遍历是升序的,本题中给出的数组刚好是升序的,相当于通过中序遍历恢复二叉搜索树
  2. 可以选择升序序列中的任意位置的元素作为根节点,该元素左边的升序序列构建左子树,右边的升序序列构建右子树
  3. 题目又要求高度平衡,所以我们需要选择升序序列的中间位置的元素作为根节点即可
constsortedArrayToBST=function(nums){constbuildTree=(Arr,left,right)=>{if(left>right)returnnullletmid=Math.floor(left+(right-left)/2)letroot=newTreeNode(Arr[mid])root.left=buildTree(Arr,left,mid-1)root.right=buildTree(Arr,mid+1,right)returnroot}returnbuildTree(nums,0,nums.length-1)}
  • 时间复杂度:O(n)
  • 空间复杂度:O(logn)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp