LeetCode 题解工作台
不同的二叉搜索树
给你一个整数 n ,求恰由 n 个节点组成且节点值从 1 到 n 互不相同的 二叉搜索树 有多少种?返回满足题意的二叉搜索树的种数。 示例 1: 输入: n = 3 输出: 5 示例 2: 输入: n = 1 输出: 1 提示: 1
5
题型
7
代码语言
3
相关题
当前训练重点
中等 · 二分·树·traversal
答案摘要
我们定义 表示 $[1, i]$ 能产生的二叉搜索树的个数,初始时 $f[0] = 1$,答案为 。 我们可以枚举节点数 ,那么左子树节点数 $j \in [0, i - 1]$,右子树节点数 $k = i - j - 1$,左子树节点数和右子树节点数的组合数为 $f[j] \times f[k]$,因此 $f[i] = \sum_{j = 0}^{i - 1} f[j] \times f[i …
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给你一个整数 n ,求恰由 n 个节点组成且节点值从 1 到 n 互不相同的 二叉搜索树 有多少种?返回满足题意的二叉搜索树的种数。
示例 1:
输入:n = 3 输出:5
示例 2:
输入:n = 1 输出:1
提示:
1 <= n <= 19
解题思路
方法一:动态规划
我们定义 表示 能产生的二叉搜索树的个数,初始时 ,答案为 。
我们可以枚举节点数 ,那么左子树节点数 ,右子树节点数 ,左子树节点数和右子树节点数的组合数为 ,因此 。
最后返回 即可。
时间复杂度 ,空间复杂度 。其中 为节点数。
class Solution:
def numTrees(self, n: int) -> int:
f = [1] + [0] * n
for i in range(n + 1):
for j in range(i):
f[i] += f[j] * f[i - j - 1]
return f[n]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you understand how dynamic programming can be applied to this problem?
- question_mark
Can you explain why the solution involves recursive subproblems?
- question_mark
Will you be able to efficiently calculate the Catalan number using a mathematical formula?
常见陷阱
外企场景- error
Not memoizing the results of subproblems, leading to redundant calculations.
- error
Incorrectly assuming that the solution can be computed in linear time without considering the complexity of recursive calls.
- error
Failing to realize that the number of BSTs grows exponentially, which may lead to inefficiencies in time complexity if not optimized.
进阶变体
外企场景- arrow_right_alt
How would the problem change if we allowed duplicate values in the BST?
- arrow_right_alt
What happens if the BST formation is restricted by some additional constraints, like balanced height?
- arrow_right_alt
How can this approach be adapted to count the number of unique AVL trees instead of BSTs?