LeetCode 题解工作台
二叉搜索树中第 K 小的元素
给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 小的元素( k 从 1 开始计数)。 示例 1: 输入: root = [3,1,4,null,2], k = 1 输出: 1 示例 2: 输入: root = [5,3,6,2,4,null,null,1],…
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 二分·树·traversal
答案摘要
由于二叉搜索树的性质,中序遍历一定能得到升序序列,因此可以采用中序遍历找出第 k 小的元素。 class Solution:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 小的元素(k 从 1 开始计数)。
示例 1:
输入:root = [3,1,4,null,2], k = 1 输出:1
示例 2:
输入:root = [5,3,6,2,4,null,null,1], k = 3 输出:3
提示:
- 树中的节点数为
n。 1 <= k <= n <= 1040 <= Node.val <= 104
进阶:如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化算法?
解题思路
方法一:中序遍历
由于二叉搜索树的性质,中序遍历一定能得到升序序列,因此可以采用中序遍历找出第 k 小的元素。
# 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 kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
stk = []
while root or stk:
if root:
stk.append(root)
root = root.left
else:
root = stk.pop()
k -= 1
if k == 0:
return root.val
root = root.right
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity ranges from O(h + k) for recursive or iterative traversal, where h is tree height, to O(log n) per query with augmented BST. Space complexity is O(h) for recursion stack or stack in iteration, or O(1) additional if using counts in augmented nodes. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Are you leveraging the BST property to avoid unnecessary traversal?
- question_mark
How do you track the count without storing all elements?
- question_mark
Can you optimize for repeated kth queries with minimal extra storage?
常见陷阱
外企场景- error
Confusing in-order traversal order in a BST and miscounting nodes.
- error
Using full tree flattening which increases space unnecessarily.
- error
Failing to stop traversal after reaching the kth element, wasting time.
进阶变体
外企场景- arrow_right_alt
Find kth largest element in a BST by reversing in-order traversal.
- arrow_right_alt
Handle dynamic BSTs with insertions and deletions while supporting kth smallest queries.
- arrow_right_alt
Compute kth smallest element in a BST with duplicates allowed, considering duplicate counts.