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;
}
相关推荐
lhbweilai1 小时前
分析FreeRTOS内核对象API的源码实现(四)
c语言·stm32·单片机
inrichtt4 小时前
第八课时:SPI总线揭秘:四线全双工通信的奥
c语言·数据结构·stm32·单片机·嵌入式硬件
HPtiger5 小时前
数据结构——选择排序
数据结构·算法·排序算法
康实训5 小时前
老年评估仿真实训平台架构设计与老年人能力评估实训室教学落地实践
大数据·人工智能·算法·实训室·实训室建设
DongQiShanRen5 小时前
六根硬件映射(四):归属澄清、两处不一致与卷十一总表
开发语言·人工智能·算法·rust·哈希算法·集成学习
CCblandy5 小时前
雪花 ID 四个边界实测:时钟回拨重号 500 个,前端 JSON.parse 直接丢精度
后端·python·算法·性能优化·架构
丑梨数据6 小时前
信创环境里跑文档工具:格式兼容与本地合规的几个坑
数据结构·人工智能·算法·决策树·排序算法
erzong2317 小时前
Linux操作系统:线程概念与控制
linux·算法
wuminyu8 小时前
JMM学习总结:深入理解happens-before关系
java·linux·c语言·jvm·c++
Nil2088 小时前
leetcode 5最长回文子串
算法·leetcode·职场和发展