⚡Flashcard Drill➔
NeetCode #392LC-108EasyTrees
← Back to All Problems

#392 · #108 · Convert Sorted Array to Binary Search Tree(将有序数组转换为二叉搜索树)

📌 Problem Statement & Constraints

Given an integer array nums sorted in ascending order, convert it to a height-balanced binary search tree. Constraints: 1 <= nums.length <= 10^4, -10^4 <= nums[i] <= 10^4; values are distinct.

💡 Core Algorithmic Approaches

  1. Choosing the middle element as the root guarantees that the left and right subtrees have nearly equal sizes, which is exactly the height-balance condition.
  2. Recurse on the two halves with the same rule.
  3. The base case is an empty range, which returns None.
  4. Because the array is sorted, the in-order traversal of the result reproduces it -- so the BST property is automatic.

💻 Benchmark Python3 Implementation

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
        def build(lo: int, hi: int) -> Optional[TreeNode]:
            if lo > hi:
                return None                # empty range
            mid = (lo + hi) // 2           # middle -> balanced
            node = TreeNode(nums[mid])
            node.left = build(lo, mid - 1)
            node.right = build(mid + 1, hi)
            return node

        return build(0, len(nums) - 1)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each element becomes exactly one node.
💾 Space Complexity
O(log n) for the recursion stack on a balanced build, plus O(n) for the nodes.

⚠️ Interview Pitfalls & Follow-ups

  • Choosing the first element as the root: the tree would degenerate into a linked list of height n.
  • Slicing the array: it works, but the index-range version avoids O(n log n) total copying.
  • Using mid = (lo + hi + 1) // 2: still balanced, just biased right; either choice is acceptable but be consistent.
  • Assuming duplicates are allowed: values are distinct, which keeps the BST property unambiguous.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Trees Problems

中文速览与面试要点

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

给你一个整数数组 nums,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。 高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1」的二叉树。约束:1 ≤ nums.length ≤ 10^4;-10^4 ≤ nums[i] ≤ 10^4;nums 按 严格递增 顺序排列。

核心要点

  • 分治 + 取中点(标准解) :每次取区间的中点作为根节点,递归构造左右子树。
  • 为什么取中点能保证平衡 :中点把区间均分为左右两半,因此左右子树的节点数之差不超过 1,高度差也就不超过 1。
  • BST 性质 :左半区间的值都小于中点,右半都大于中点,因此天然满足 BST 要求。
  • 复杂度 :O(n) 时间(每个元素建一个节点)、O(log n) 空间(递归栈)。

常见陷阱

  • 取 (l + r) // 2 之外的划分方式 :如总是取左端点,会退化成链表,不满足「高度平衡」。
  • 递归终止条件写成 l &gt;= r :会漏掉叶子节点。应为 l &gt; r 。
  • 忘记返回 node :递归返回值必须挂到父节点。
  • 中点的选择影响结果但不影响正确性 :取 (l+r)//2 或 (l+r+1)//2 都是合法答案,题目允许多解。

参考实现

class Solution:
    def sortedArrayToBST(self, nums: list[int]) -> 'TreeNode':
        def build(l: int, r: int) -> 'TreeNode':
            if l > r:
                return None
            mid = (l + r) // 2              # 取中点作为根
            node = TreeNode(nums[mid])
            node.left = build(l, mid - 1)
            node.right = build(mid + 1, r)
            return node

        return build(0, len(nums) - 1)