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;
}
相关推荐
oplp18 小时前
第四章 C语言中的基本输入输出(六)
c语言
程序员东岸20 小时前
《数据结构——排序(中)》选择与交换的艺术:从直接选择到堆排序的性能跃迁
数据结构·笔记·算法·leetcode·排序算法
程序员-King.20 小时前
day104—对向双指针—接雨水(LeetCode-42)
算法·贪心算法
神仙别闹20 小时前
基于C++实现(控制台)应用递推法完成经典型算法的应用
开发语言·c++·算法
Ayanami_Reii20 小时前
进阶数据结构应用-一个简单的整数问题2(线段树解法)
数据结构·算法·线段树·延迟标记
listhi52021 小时前
基于改进SET的时频分析MATLAB实现
开发语言·算法·matlab
Keep_Trying_Go1 天前
基于Zero-Shot的目标计数算法详解(Open-world Text-specified Object Counting)
人工智能·pytorch·python·算法·多模态·目标统计
xl.liu1 天前
零售行业仓库商品数据标记
算法·零售
confiself1 天前
通义灵码分析ms-swift框架中CHORD算法实现
开发语言·算法·swift