LeetCode 题解工作台
有序链表转换二叉搜索树
给定一个单链表的头节点 head ,其中的元素 按升序排序 ,将其转换为 平衡 二叉搜索树。 示例 1: 输入: head = [-10,-3,0,5,9] 输出: [0,-3,9,-10,null,5] 解释: 一个可能的答案是[0,-3,9,-10,null,5],它表示所示的高度平衡的二叉搜索…
5
题型
8
代码语言
3
相关题
当前训练重点
中等 · 链表指针操作
答案摘要
我们先将链表转换为数组 ,然后使用深度优先搜索构造二叉搜索树。 我们定义一个函数 $\textit{dfs}(i, j)$,其中 和 表示当前区间为 $[i, j]$。每次我们选择区间中间位置 的数字作为根节点,递归地构造左侧区间 $[i, \textit{mid} - 1]$ 的子树,以及右侧区间 $[\textit{mid} + 1, j]$ 的子树。最后返回 对应的节点作为当前子树的…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路
题目描述
给定一个单链表的头节点 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
解题思路
方法一:DFS
我们先将链表转换为数组 ,然后使用深度优先搜索构造二叉搜索树。
我们定义一个函数 ,其中 和 表示当前区间为 。每次我们选择区间中间位置 的数字作为根节点,递归地构造左侧区间 的子树,以及右侧区间 的子树。最后返回 对应的节点作为当前子树的根节点。
在主函数中,我们只需要调用 并返回即可。
时间复杂度 ,空间复杂度 。其中 是链表的长度。
# 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)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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?
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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).