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;
}
相关推荐
moonsims9 分钟前
Z3 Technology-适用于无人机和机器人的 4K 高清摄像机和视频编码器
算法
摘星编程18 分钟前
深入浅出 Tokio 源码:掌握 Rust 异步编程的底层逻辑
网络·算法·rust·系统编程·tokio
小龙报30 分钟前
《数组和函数的实践游戏---扫雷游戏(基础版附源码)》
c语言·开发语言·windows·游戏·创业创新·学习方法·visual studio
Hard_Liquor44 分钟前
Datawhale秋训营-“大运河杯”数据开发应用创新大赛
人工智能·深度学习·算法
liu****1 小时前
笔试强训(八)
开发语言·算法·1024程序员节
草莓工作室1 小时前
数据结构14:查找
数据结构·算法
逐步前行1 小时前
C数据结构--线性表(顺序表|单链表|双向链表)
c语言·数据结构·链表
草莓工作室2 小时前
数据结构13:排序
c语言·数据结构·排序算法
屈冠成2 小时前
C语言数组:编辑世界的坚固桥梁
c语言·开发语言·算法
应用市场2 小时前
STM32卡尔曼滤波算法详解与实战应用
人工智能·stm32·算法