⚡Flashcard Drill➔
NeetCode #448LC-95MediumTrees
← Back to All Problems

#448 · #95 · Unique Binary Search Trees II(不同的二叉搜索树 II)

📌 Problem Statement & Constraints

Given an integer n, return all structurally unique binary search trees that store the values 1..n. Return the roots in any order. Constraints: 1 <= n <= 8.

💡 Core Algorithmic Approaches

  1. Recursively build all trees over a value range [lo, hi].
  2. For each candidate root value v, combine every left tree over [lo, v-1] with every right tree over [v+1, hi].
  3. The base case lo > hi returns a single None, representing an empty subtree.
  4. The total output is the Catalan number, which is why n is capped at 8.

💻 Benchmark Python3 Implementation

class Solution:
    def generateTrees(self, n: int) -> List[Optional[TreeNode]]:
        def build(lo: int, hi: int) -> List[Optional[TreeNode]]:
            if lo > hi:
                return [None]              # one empty subtree
            res = []
            for v in range(lo, hi + 1):    # v is the root value
                for l in build(lo, v - 1):
                    for r in build(v + 1, hi):
                        res.append(TreeNode(v, l, r))
            return res

        return build(1, n) if n else []


# Memoised variant: reuse the trees for each (lo, hi) range
class Solution2:
    def generateTrees(self, n: int) -> List[Optional[TreeNode]]:
        from functools import lru_cache

        @lru_cache(maxsize=None)
        def build(lo: int, hi: int):
            if lo > hi:
                return (None,)
            res = []
            for v in range(lo, hi + 1):
                for l in build(lo, v - 1):
                    for r in build(v + 1, hi):
                        res.append(TreeNode(v, l, r))
            return tuple(res)

        return list(build(1, n)) if n else []

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n * Catalan(n)): each generated tree requires O(n) node creations.
💾 Space Complexity
O(Catalan(n)) for the output, plus O(n) recursion depth.

⚠️ Interview Pitfalls & Follow-ups

  • Returning [] for the empty range instead of [None]: then no tree would ever be built, since the loops iterate over the child lists.
  • Reusing the same subtree objects across different trees: the memoised variant shares nodes, which mutates shared structure if the caller modifies the trees -- acceptable for this problem but worth noting.
  • Trying to deduplicate structurally identical trees: distinct root values always give distinct BSTs, so no deduplication is needed.
  • Using a value range based on 0: the values are 1..n.
⚡
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

中文速览与面试要点

不同的二叉搜索树 II

给你一个整数 n,请你生成并返回所有由 n 个节点组成且节点值从 1 到 n 互不相同的不同 二叉搜索树 。可以按 任意顺序 返回答案。约束:1 ≤ n ≤ 8。

核心要点

  • 递归生成所有组合(标准解) :对区间 [l, r] ,枚举根的值 k;递归生成左子树的所有可能 build(l, k−1) 与右子树的所有可能 build(k+1, r) ,然后做 笛卡尔积 组合。
  • 为什么用笛卡尔积 :每一种左子树形态都能与每一种右子树形态组合,得到一种完整的树。
  • 终止条件 : l &gt; r 时返回 [None] (一个空树),这样笛卡尔积在叶子处仍能正确工作。
  • 复杂度 :生成的树总数是卡特兰数 C(2n, n)/(n+1) ,n = 8 时为 1430,规模可接受。

常见陷阱

  • l &gt; r 时返回 [] :会让笛卡尔积为空,导致整棵树无法生成。必须返回 [None] 。
  • n == 0 时返回 [None] :题目要求返回空列表(n ≥ 1)。
  • 只生成一种左右子树组合 :必须用双重循环做笛卡尔积。
  • n 较大时用本解法 :卡特兰数增长极快,n &gt; 10 时内存会爆。本题 n ≤ 8 是前提。

参考实现

class Solution:
    def generateTrees(self, n: int) -> list:
        def build(l: int, r: int) -> list:
            if l > r:
                return [None]           # 空树也算一种形态
            res = []
            for k in range(l, r + 1):   # 枚举根
                for left in build(l, k - 1):
                    for right in build(k + 1, r):
                        res.append(TreeNode(k, left, right))
            return res

        return build(1, n) if n else []