【 每天学习一点算法 2026/03/14】二叉搜索树中第K小的元素

每天学习一点算法 2026/03/14

题目:二叉搜索树中第K小的元素

给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 小的元素(k 从 1 开始计数)。

  1. 首先想到的就是先遍历,再排序,再找到第 k 小的元素

    typescript 复制代码
    /**
     * Definition for a binary tree node.
     * class TreeNode {
     *     val: number
     *     left: TreeNode | null
     *     right: TreeNode | null
     *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
     *         this.val = (val===undefined ? 0 : val)
     *         this.left = (left===undefined ? null : left)
     *         this.right = (right===undefined ? null : right)
     *     }
     * }
     */
    
    function kthSmallest(root: TreeNode | null, k: number): number {
      const res: number[] = []
      function helper (root: TreeNode | null) {
        if (root === null) return null
        res.push(root.val)
        helper(root.left)
        helper(root.right)
      }
      helper(root)
      return res.sort((a, b) => a - b)[k - 1]
    };
  2. 根据二叉树的特性:每个节点的左子树的结点一定比这个节点小,右子树的结点一定比这个节点大,那么二叉树的中序遍历结果一定是递增的,所以我们可以省去排序的步骤

    typescript 复制代码
    function kthSmallest(root: TreeNode | null, k: number): number {
      const res: number[] = []
      function helper (root: TreeNode | null) {
        if (root === null) return null
        helper(root.left)
        res.push(root.val)
        helper(root.right)
      }
      helper(root)
      return res[k - 1]
    };

题目来源:力扣(LeetCode)

相关推荐
弗锐土豆17 分钟前
自动化-程序员从抽象与具象的角度学习自动化
学习·程序员·自动化·抽象·具象
bush421 分钟前
嵌入式linux学习记录十二,mmap
java·linux·学习
嵌入式老牛22 分钟前
液晶段码(米/日字格)识别—倾斜校正
opencv·算法·仿射变换
luj_176824 分钟前
残熵算法:风险缓冲与效率优化的融合
c语言·开发语言·网络·经验分享·算法
共享家95271 小时前
OpenClaw的通道配置
人工智能·学习·openclaw
oddsand11 小时前
pgvector 三大相似度算法
人工智能·算法·机器学习
运筹vivo@1 小时前
LeetCode 2574. 左右元素和的差值
算法·leetcode·职场和发展·每日一题
计算机安禾1 小时前
【数据库系统原理】第4篇:关系数据结构的形式化定义:域、笛卡尔积与关系模式
数据结构·数据库·算法
手写码匠2 小时前
手写 DeepSeek 推理引擎优化:从 FP16 到 INT4 的量化加速实战
人工智能·深度学习·算法·aigc
GuWenyue2 小时前
LeetCode 76 最小覆盖子串|JS 滑动窗口标准解法
前端·算法·面试