LeetCode 题解工作台

将有序数组转换为二叉搜索树

给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 平衡 二叉搜索树。 示例 1: 输入: nums = [-10,-3,0,5,9] 输出: [0,-3,9,-10,null,5] 解释: [0,-10,5,null,-3,null,9] 也将被视为正确答案: 示例 2:…

category

5

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 二分·树·traversal

bolt

答案摘要

我们设计一个递归函数 $\textit{dfs}(l, r)$,表示当前待构造的二叉搜索树的节点值都在数组 的下标范围 $[l, r]$ 内。该函数返回构造出的二叉搜索树的根节点。 函数 $\textit{dfs}(l, r)$ 的执行流程如下:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 平衡 二叉搜索树。

 

示例 1:

输入:nums = [-10,-3,0,5,9]
输出:[0,-3,9,-10,null,5]
解释:[0,-10,5,null,-3,null,9] 也将被视为正确答案:

示例 2:

输入:nums = [1,3]
输出:[3,1]
解释:[1,null,3] 和 [3,1] 都是高度平衡二叉搜索树。

 

提示:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums严格递增 顺序排列
lightbulb

解题思路

方法一:二分 + 递归

我们设计一个递归函数 dfs(l,r)\textit{dfs}(l, r),表示当前待构造的二叉搜索树的节点值都在数组 nums\textit{nums} 的下标范围 [l,r][l, r] 内。该函数返回构造出的二叉搜索树的根节点。

函数 dfs(l,r)\textit{dfs}(l, r) 的执行流程如下:

  1. 如果 l>rl > r,说明当前数组为空,返回 null
  2. 如果 lrl \leq r,取数组中下标为 mid=l+r2\textit{mid} = \lfloor \frac{l + r}{2} \rfloor 的元素作为当前二叉搜索树的根节点,其中 x\lfloor x \rfloor 表示对 xx 向下取整。
  3. 递归地构造当前二叉搜索树的左子树,其根节点的值为数组中下标为 mid1\textit{mid} - 1 的元素,左子树的节点值都在数组的下标范围 [l,mid1][l, \textit{mid} - 1] 内。
  4. 递归地构造当前二叉搜索树的右子树,其根节点的值为数组中下标为 mid+1\textit{mid} + 1 的元素,右子树的节点值都在数组的下标范围 [mid+1,r][\textit{mid} + 1, r] 内。
  5. 返回当前二叉搜索树的根节点。

答案即为函数 dfs(0,n1)\textit{dfs}(0, n - 1) 的返回值。

时间复杂度 O(n)O(n),空间复杂度 O(logn)O(\log n)。其中 nn 为数组 nums\textit{nums} 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
        def dfs(l: int, r: int) -> Optional[TreeNode]:
            if l > r:
                return None
            mid = (l + r) >> 1
            return TreeNode(nums[mid], dfs(l, mid - 1), dfs(mid + 1, r))

        return dfs(0, len(nums) - 1)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Do you see that choosing the middle element is what satisfies both BST ordering and height balance at the same time?

  • question_mark

    Can you explain why using left and right indices is safer here than repeatedly slicing the array into subarrays?

  • question_mark

    Will you handle even-length ranges consistently and show that either middle choice still produces a valid height-balanced BST?

warning

常见陷阱

外企场景
  • error

    Using the first or last element as each root, which preserves BST order but creates a skewed tree instead of a height-balanced one.

  • error

    Recursing on the wrong ranges, such as including mid in a child call again, which causes infinite recursion or duplicate nodes.

  • error

    Building with array slices everywhere, which still works logically but quietly increases memory use and can hurt performance on large inputs.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Convert a sorted singly linked list to a height-balanced BST, where random access is gone and midpoint handling changes.

  • arrow_right_alt

    Build the BST iteratively from a sorted array using an explicit queue or stack of index ranges instead of recursion.

  • arrow_right_alt

    Given a sorted array, return any height-balanced BST but prefer the left middle or right middle consistently for even-length segments.

help

常见问题

外企场景

将有序数组转换为二叉搜索树题解:二分·树·traversal | LeetCode #108 简单