LeetCode 题解工作台

有序链表转换二叉搜索树

给定一个单链表的头节点 head ,其中的元素 按升序排序 ,将其转换为 平衡 二叉搜索树。 示例 1: 输入: head = [-10,-3,0,5,9] 输出: [0,-3,9,-10,null,5] 解释: 一个可能的答案是[0,-3,9,-10,null,5],它表示所示的高度平衡的二叉搜索…

category

5

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

中等 · 链表指针操作

bolt

答案摘要

我们先将链表转换为数组 ,然后使用深度优先搜索构造二叉搜索树。 我们定义一个函数 $\textit{dfs}(i, j)$,其中 和 表示当前区间为 $[i, j]$。每次我们选择区间中间位置 的数字作为根节点,递归地构造左侧区间 $[i, \textit{mid} - 1]$ 的子树,以及右侧区间 $[\textit{mid} + 1, j]$ 的子树。最后返回 对应的节点作为当前子树的…

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个单链表的头节点  head ,其中的元素 按升序排序 ,将其转换为 平衡 二叉搜索树。

 

示例 1:

输入: head = [-10,-3,0,5,9]
输出: [0,-3,9,-10,null,5]
解释: 一个可能的答案是[0,-3,9,-10,null,5],它表示所示的高度平衡的二叉搜索树。

示例 2:

输入: head = []
输出: []

 

提示:

  • head 中的节点数在[0, 2 * 104] 范围内
  • -105 <= Node.val <= 105
lightbulb

解题思路

方法一:DFS

我们先将链表转换为数组 nums\textit{nums},然后使用深度优先搜索构造二叉搜索树。

我们定义一个函数 dfs(i,j)\textit{dfs}(i, j),其中 iijj 表示当前区间为 [i,j][i, j]。每次我们选择区间中间位置 mid\textit{mid} 的数字作为根节点,递归地构造左侧区间 [i,mid1][i, \textit{mid} - 1] 的子树,以及右侧区间 [mid+1,j][\textit{mid} + 1, j] 的子树。最后返回 mid\textit{mid} 对应的节点作为当前子树的根节点。

在主函数中,我们只需要调用 dfs(0,n1)\textit{dfs}(0, n - 1) 并返回即可。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 是链表的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
# 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 sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
        def dfs(i: int, j: int) -> Optional[TreeNode]:
            if i > j:
                return None
            mid = (i + j) >> 1
            l, r = dfs(i, mid - 1), dfs(mid + 1, j)
            return TreeNode(nums[mid], l, r)

        nums = []
        while head:
            nums.append(head.val)
            head = head.next
        return dfs(0, len(nums) - 1)
speed

复杂度分析

指标
时间complexity depends on the approach: splitting lists recursively is O(n log n), whereas inorder simulation achieves O(n). Space complexity is O(log n) due to recursion stack in a balanced BST. Using pointer manipulation avoids extra arrays, reducing overhead compared to naive list copying, making this solution memory-efficient while maintaining height balance.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Do you correctly find the middle node without extra list creation?

  • question_mark

    Can you maintain pointer integrity while recursively constructing left and right subtrees?

  • question_mark

    Will you handle empty and single-node lists without causing null pointer errors?

warning

常见陷阱

外企场景
  • error

    Failing to disconnect the left sublist causes cycles or incorrect subtree connections.

  • error

    Using list slicing instead of pointer manipulation increases space and breaks the O(n) expectation.

  • error

    Incorrect middle selection in even-length lists can unbalance the BST or violate height-balance requirement.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Convert Sorted Array to BST (array-based version with direct index access).

  • arrow_right_alt

    Balanced BST to Sorted Linked List (reverse pattern requiring inorder traversal).

  • arrow_right_alt

    Convert Sorted Circular Linked List to BST (requires handling circular pointer traversal).

help

常见问题

外企场景

有序链表转换二叉搜索树题解:链表指针操作 | LeetCode #109 中等