【 每天学习一点算法 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)

相关推荐
Xudde.4 小时前
班级作业笔记报告0x04
笔记·学习·安全·web安全·php
CoderCodingNo4 小时前
【NOIP】2011真题解析 luogu-P1003 铺地毯 | GESP三、四级以上可练习
算法
晓晓hh4 小时前
JavaSE学习——迭代器
java·开发语言·学习
iFlyCai4 小时前
C语言中的指针
c语言·数据结构·算法
查古穆4 小时前
栈-有效的括号
java·数据结构·算法
再一次等风来5 小时前
近场声全息(NAH)仿真实现:从阵列实值信号到波数域重建
算法·matlab·信号处理·近场声全息·nah
汀、人工智能5 小时前
16 - 高级特性
数据结构·算法·数据库架构·图论·16 - 高级特性
大熊背5 小时前
利用ISP离线模式进行分块LSC校正的方法
人工智能·算法·机器学习
XWalnut5 小时前
LeetCode刷题 day4
算法·leetcode·职场和发展
421!5 小时前
GPIO工作原理以及核心
开发语言·单片机·嵌入式硬件·学习