150强访谈简单

BST 中的第 K 个最小元素

“BST 中的第 K 个最小元素”问题的详细指南和 Python 实现。

问题陈述

简单

给定二叉搜索树的根和整数 k,返回树中所有节点值的第 k 个最小值(1 索引)。

该树被表示为一个级别顺序列表。实现函数 kthSmallest(root: list, k: int) -> int

约束条件
  • The number of nodes in the tree is n
  • 1 <= k <= n <= 10000
  • 0 <= Node.val <= 10000

示例

Example 1
Input
[3,1,4,None,2], 1
Output
1
Explanation

The in-order traversal is [1,2,3,4]. The 1st smallest is 1.

Example 2
Input
[5,3,6,2,4,None,None,1], 3
Output
3
Explanation

The in-order traversal is [1,2,3,4,5,6]. The 3rd smallest is 3.

Need a Hint?
考虑使用树特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。