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],…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·树·traversal

bolt

答案摘要

由于二叉搜索树的性质,中序遍历一定能得到升序序列,因此可以采用中序遍历找出第 k 小的元素。 class Solution:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个二叉搜索树的根节点 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 <= 104
  • 0 <= Node.val <= 104

 

进阶:如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化算法?

lightbulb

解题思路

方法一:中序遍历

由于二叉搜索树的性质,中序遍历一定能得到升序序列,因此可以采用中序遍历找出第 k 小的元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 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
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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?

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

二叉搜索树中第 K 小的元素题解:二分·树·traversal | LeetCode #230 中等