LeetCode //C - 230. Kth Smallest Element in a BST

230. Kth Smallest Element in a BST

Given the root of a binary search tree, and an integer k , return the k t h k^{th} kth smallest value (1-indexed) of all the values of the nodes in the tree.

Example 1:

Input: root = [3,1,4,null,2], k = 1
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3

Constraints:
  • The number of nodes in the tree is n.
  • 1 < = k < = n < = 1 0 4 1 <= k <= n <= 10^4 1<=k<=n<=104
  • 0 < = N o d e . v a l < = 1 0 4 0 <= Node.val <= 10^4 0<=Node.val<=104

From: LeetCode

Link: 230. Kth Smallest Element in a BST


Solution:

Ideas:

Here's how the algorithm will work:

  1. Perform an in-order traversal of the BST.
  2. As you traverse the nodes, keep a count of the nodes visited.
  3. When the count becomes equal to k, that node's value is the kth smallest. current node and the previous node.
Code:
c 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
typedef struct {
    int count;
    int value;
} Result;

void inOrderTraversal(struct TreeNode* root, int k, Result* res) {
    if (root == NULL || res->count == k) return;

    inOrderTraversal(root->left, k, res);
    if (++res->count == k) {
        res->value = root->val;
    }
    inOrderTraversal(root->right, k, res);
}

int kthSmallest(struct TreeNode* root, int k) {
    Result res = {0, 0};
    inOrderTraversal(root, k, &res);
    return res.value;
}
相关推荐
NAGNIP17 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队18 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶1 天前
算法 --- 字符串
算法
博笙困了1 天前
AcWing学习——差分
c++·算法
NAGNIP1 天前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP1 天前
大模型微调框架之LLaMA Factory
算法
echoarts1 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客1 天前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法